strust2页面分发机制模拟

模拟步骤:

一、 监听器
1、 准备一个map
2、 把所有的action的key,value放入到map中
3、 把map放入到application域中
二、 过滤器
1、 获取application域中的map
2、 解析url
3、 根据解析的url从map中把value提取出来
4、 根据java的反射机制动态调用action
5、 根据action返回的方法跳转到相应的页面
三、执行action 的execute方法,该方法返回一个字符串


(1)监听器加载map
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ServletListener implements ServletContextListener {
	//tomcat关闭的时候被调用
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		arg0.getServletContext().removeAttribute("maping");
		System.out.println("监听器被摧毁!");
	}
	//tomcat启动的时候被加载
	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		Map<String,String> map  = new HashMap<String,String>();
		map.put("Myaction", "com.itheima.structstest.Myaction");
		arg0.getServletContext().setAttribute("maping", map);
		System.out.println("监听器被初始化了----------------------------------------------!");
	}

}


(2)编写Action类返回要调用的结果

public class Myaction {
	
	public String execute() {
		return "index.jsp";	//返回一个需要跳转的页面
	}
}


(3)编写过滤器完成对后缀为.action的请求过滤
public class FilterControl implements Filter {
	private FilterConfig myConfig;
	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)arg0;
		HttpServletResponse response = (HttpServletResponse)arg1;
		//获取监听器中存储的map
		Map<String,String> map =
				(Map<String,String>)myConfig.getServletContext().getAttribute("maping");
		
		//获取请求的URI中具体的请求Action
		String key = ActionUtil(request.getRequestURI());
		//获取对应action在map中的类
		String obj = (String)map.get(key);
		//一下功能室通过反射原理调用相应的方法,得到需要的转发页面,然后进行转发
		try {
			Class clazz = Class.forName(obj);
			System.out.println(clazz);
			Method me = clazz.getMethod("execute", null);
			String exem = (String)me.invoke(clazz.newInstance(), null);
			
			request.getRequestDispatcher(exem).forward(request, response);
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		
	}
	
	public String  ActionUtil(String url) {
		
		String[] str = url.split("/");
		String lastStr = str[str.length-1];
		return  lastStr.substring(0,lastStr.indexOf("."));
	}
	
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		this.myConfig = arg0;
	}

}

(4)web.xml中的配置
<listener>
  <listener-class>com.itheima.structstest.ServletListener</listener-class>
  </listener>
  <filter>
  		<filter-name>FilterControl</filter-name>
  		<filter-class>com.itheima.structstest.FilterControl</filter-class>
  </filter>
  <filter-mapping>
  		<filter-name>FilterControl</filter-name>
  		<url-pattern>*.action</url-pattern>
  </filter-mapping>

(5)请求测试
http://localhost:8080/test/Myaction.action   //请求Myaction的资源


你可能感兴趣的:(strust2页面分发机制模拟)