java重构ActionServlet,减少Web.xml的配置项代码量
程序员文章站
2022-04-23 23:20:32
Servlet 的致命的两个缺点(面试题): ActionServlet的实现步骤: 1、创建Action接口 : 2、创建一个Action 重写Action接口的处理方法: 3、创建ActionFilter过滤器(实现Filter接口 重写 Filter生命周期的方法): 解析URI的getAct ......
Servlet 的致命的两个缺点(面试题):
- web.xml 文件配置项比较多 原因:由于Servlet的增多,会产生大量的Servlet配置
- Servlet 具有容器依赖性 原因:servlet在处理get或post请求时,HttpServletRequest和HttpServletResponse对象由Web容器创建
ActionServlet的实现步骤:
1、创建Action接口 :
public interface Action { public String execute(HttpServletRequest request,HttpServletResponse response); }
2、创建一个Action 重写Action接口的处理方法:
public class HelloWorld implements Action{ @Override public String execute(HttpServletRequest request, HttpServletResponse response) { System.out.println("action 访问成功!"); //提示Action的处理方法被执行 return "index.jsp"; //返回要重定向的jsp地址 } }
3、创建ActionFilter过滤器(实现Filter接口 重写 Filter生命周期的方法):
public class ActionFilter implements Filter{ private HttpServletRequest request = null; private HttpServletResponse response = null; @Override public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //拿到Http的响应和请求对象 this.request = (HttpServletRequest)request; this.response = (HttpServletResponse)response; //获取过滤到的Action 地址的URI String uri = this.request.getRequestURI(); //解析出来要访问的Action的名字 String actionName = ActionUtil.getAction(uri); try { //利用反射机制创建要访问的Action Action action = (Action)Class.forName("th.action."+actionName).newInstance(); //调用要访问的Action的处理方法 并且把HTTP的响应和请求传给Action String page = action.execute(this.request, this.response); //根据Action返回的page页面名字进行重定向 this.request.getRequestDispatcher(page).forward(this.request, this.response); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void destroy() { // TODO Auto-generated method stub } }
解析URI的getAction()方法:
public class ActionUtil { public static String getActionName(String uri){ String[] str = uri.split("/"); String result = str[str.length-1].substring(0, str[str.length-1].indexOf(".")); return result; } }
4、在Web.xml配置Filter过滤器:
<filter> <filter-name>ActionFilter</filter-name> <filter-class>th.filter.ActionFilter</filter-class> </filter> <filter-mapping> <filter-name>ActionFilter</filter-name> <url-pattern>*.action</url-pattern> <!--根据后缀以*.action结尾的地址来区别要访问的是Action还是Servlet--> </filter-mapping>
5、创建一个测试jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title></title> </head> <body> <a href="HelloWorld.action" >请求一个action</a> //通过href="*.action" 来区别访问的是Sevlet还是Action </body> </html>
下一篇: 互联网创业该学习腾讯:伟大的艺术家靠抄袭