针对servlet的缺点,可以对servlet进行重构,使其开发起来更简便,更容易,更适合团队开发。
重构的目标:
1.只写一个servlet或者只写过滤器.
2.不用再写其它的serlvet,这样可以减少web.xml这个配置文件中的代码
3.原来需要写的servlet,改写成action
3.在action中把HttpServletRequest和HttpServletResponse参数传递过去
4.在过滤器中就采用java的反射机制来调用action
eg:
做一个转发过滤器
public void doFilter(ServletRequest request, ServletResponse response,FilterChain arg2) throws IOException, ServletException {
this.request = (HttpServletRequest)request;
this.response = (HttpServletResponse)response;
//获取请求路径
String uri = this.request.getRequestURI();
String actionName = ServletUtils.convert(uri);
//利用java的反射机制调用该方法
try {
Action action = (Action)Class.forName(actionName).newInstance();
//forward指定要跳转到的jsp页面
String forward = action.execute(this.request, this.response);
// 跳转的方法
// * 重定向
// request里的参数不起作用
// this.response.sendRedirect(jsp页面);
// * 转发
// 放在request作用域里的值可以取出来
this.request.getRequestDispatcher("index.jsp").forward(this.request, this.response);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
转载于:https://blog.51cto.com/yemaozi/1168011