Struts2工作原理模拟

来源:互联网 发布:js中substring源码 编辑:程序博客网 时间:2024/04/30 11:12
这篇文章模拟Struts2的工作原理
下面是客户端测试页面test.jsp的代码
<%@ page language="java" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%><html>  <head>    <title>My JSP 'index.jsp' starting page</title>    </head>  <body>       入门的路径:<br>        <a href="${pageContext.request.contextPath}/primer/userAction.action">userWorld</a><br>      <br>      <a href="${pageContext.request.contextPath}/helloWorld/helloWorldAction.action">helloWorld</a><br>  </body></html>
下面是两个请求链接执行的action类的代码UserAction.java 和 HelloWorldAction.java 都实现了Action接口
<pre name="code" class="java">public interface Action {public String execute();}


public class UserAction implements Action {public String execute() {System.out.println("UserAction ********** execute()");return "success";}}

public class HelloWorldAction implements Action {public String execute() {System.out.println("HelloWorldAction ********** execute()");return "success";}}

下面用Struts2Filter.java模拟Struts2过滤器
public class Struts2Filter implements Filter {Map<String, String> map = new HashMap<String, String>();public void init(FilterConfig config) throws ServletException {map.put("/primer/userAction.action", "com.edu2act.action.UserAction");map.put("/helloWorld/helloWorldAction.action", "com.edu2act.action.HelloWorldAction");}public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {//强转HttpServletRequest req = (HttpServletRequest)request;HttpServletResponse res = (HttpServletResponse)response;String path = req.getServletPath();System.out.println("path = "+path);if(path.equals("/test.jsp")){chain.doFilter(req, res);}else{try {Action action;//利用反射,通过newInstance()得到实例化action = (Action)Class.forName(map.get(path)).newInstance();action.execute();req.getRequestDispatcher("/success.jsp").forward(req, res);} catch (InstantiationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public void destroy() {// TODO Auto-generated method stub}}


0 0