一、@Action註解聲明 html
package com.togogo.webtoservice.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(value=ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Action { // String namespace() default ""; }
二、@Path註解聲明 java
package com.togogo.webtoservice.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 若是放在類上面,表示名命空間 * 若是放在方法上面,表示路徑 * @author Administrator * */ @Target(value={ElementType.TYPE,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Path { String value(); }
三、ActionExecute類
package com.togogo.webtoservice; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.togogo.webtoservice.annotations.Action; import com.togogo.webtoservice.annotations.Path; /** * 必須的問題 一、判斷傳進來的類的對象是否是一個Action 二、經過url,直接調用於Action的方法 三、返回轉路徑 * * @author Administrator * */ public class ActionExecute { private Object action; private Class<? extends Object> actionClass; private HttpServletRequest request; private HttpServletResponse response; ActionExecute(Object o, HttpServletRequest request, HttpServletResponse response) { this.action = o; this.actionClass = this.action.getClass(); this.request = request; this.response = response; } /** * 得到命名空間 * * @return */ private String getNamespace() { Path pathAnnotation = actionClass.getAnnotation(Path.class); if (pathAnnotation != null) { return pathAnnotation.value(); } else { return null; } } /** * 判斷是不是一個Action * * @return */ private boolean isAction() { Action actionAnnotation = actionClass.getAnnotation(Action.class); if (actionAnnotation == null) { return false; } else { return true; } } /** * 得到方法 * * @return */ private Method getMethod() { String uri = request.getRequestURI(); Method[] methods = actionClass.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { Method m = methods[i]; Path path = m.getAnnotation(Path.class); if (this.getNamespace() != null) { if (uri.contains(this.getNamespace())) { if (path != null) { if (uri.contains(path.value())) { return m; } } }else{ System.out.println("--命名空間不匹配--"); return null; } } else { if (path != null) { if (uri.contains(path.value())) { return m; } } } } return null; } String execute() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { if (isAction()) { Method method = this.getMethod(); String rePath = (String) method.invoke(action, request, response); return rePath; } else { System.out.println("--這不是一個Action--"); return null; } } }
四、核心控制器web
package com.togogo.webtoservice; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DispacherServlet extends HttpServlet { private static String config=null; private static String enconding="UTF-8"; @Override public void init(ServletConfig config) throws ServletException { String initConfig=config.getInitParameter("config"); String initEnconding=config.getInitParameter("enconding"); if(initConfig!=null){ DispacherServlet.config=initConfig; } //經過web描述符文件web.xml配置 if(initEnconding!=null){ DispacherServlet.enconding=initEnconding; } super.init(config); } /** * 接收任何請求, */ @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { request.setCharacterEncoding(enconding); response.setCharacterEncoding(enconding); String uri = request.getRequestURI(); StringBuilder sb = new StringBuilder(uri); String path = sb.substring(uri.lastIndexOf("/") + 1, uri.lastIndexOf("!")); System.out.println(path); String className = Config.getClassName(path,config); Object action = ActionFactory.create(className); ActionExecute actionExecute =new ActionExecute(action,request, response); String result = actionExecute.execute(); if (result.contains(":")) { StringBuilder resultStr = new StringBuilder(result); String rePath=resultStr.substring(result.indexOf(":")+1, result.length()); if(result.contains("redirect:")){ response.sendRedirect(rePath); }else if(result.contains("forward:")){ request.getRequestDispatcher(rePath).forward(request, response); } } else { request.getRequestDispatcher(result).forward(request, response); } } catch (Exception e) { e.printStackTrace(); } } }
五、Action對象工廠mvc
package com.togogo.webtoservice; /** * 一個建立Action的工廠 * @author Administrator * */ public class ActionFactory { public static Object create(String className){ Object action=null; try { action = (Object)Class.forName(className).newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return action; } }
六、配置文件類app
package com.togogo.webtoservice; import java.util.HashMap; import java.util.Map; import java.util.ResourceBundle; /** * 路徑與類名映身 * * @author Administrator * */ public class Config { // private static Map<String, String> classNames = new HashMap<String, // String>(); /** * 經過key * * @param key * @return */ public static String getClassName(String key, String config) { ResourceBundle bundle = null; if (config == null||"".equals(config)) { bundle = ResourceBundle.getBundle("Action"); } else { bundle = ResourceBundle.getBundle(config); } return bundle.getString(key); } }
--------------------------------------------------------測試框架------------------------------------------------框架
七、UserAction類jsp
package com.togogo.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.togogo.webtoservice.annotations.Action; import com.togogo.webtoservice.annotations.Path; @Action public class UserAction { /** * 用戶登陸 * * @param request * @param response * @return */ @Path(value="login.do") public String login(HttpServletRequest request, HttpServletResponse response) { System.out.println("我在登陸"); System.out.println("我在登陸."); System.out.println("我在登陸.."); System.out.println("我在登陸."); System.out.println("我在登陸.."); System.out.println("我在登陸."); System.out.println("我在登陸.."); System.out.println("我在------登陸.."); System.out.println("我在------登陸.."); System.out.println("我在------登陸.."); System.out.println("我在------登陸.."); return "main.jsp"; } /** * 用戶註冊 * * @param request * @param response * @return */ @Path(value="register.do") public String register(HttpServletRequest request, HttpServletResponse response) { System.out.println("我在註冊"); return "forward:main.jsp"; } /** * 用戶註冊 * * @param request * @param response * @return */ public String undo(HttpServletRequest request, HttpServletResponse response) { System.out.println("我在撤消"); return "redirect:main.jsp"; } }
八、映射配置文件Action.propertieside
user=com.togogo.action.UserAction
九、web.xml配置post
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>web_mvc_webtoservice</display-name> <!-- 這是一個核心控制器 --> <servlet> <servlet-name>dispacherServlet</servlet-name> <servlet-class>com.togogo.webtoservice.DispacherServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>resources.Action</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dispacherServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
十、測試頁面測試
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <a></a> <form action="${pageContext.request.contextPath }/user!login.do" method="post"> <!-- <input name="clasName" value="com.togogo.action.UserAction"> --> <input type="submit"> </form> </body> </html>
源碼下載:
http://files.cnblogs.com/files/zhuyuejiu/web_mvc_webtoservice_annotation.zip