
课程咨询: 400-996-5531 / 投诉建议: 400-111-8989
认真做教育 专心促就业
昆明IT培训的老今天给大家讲使用Filter作为控制器。
1. MVC设计模式概览
实现MVC(Model、View、Controller)模式的应用程序由3大部分构成:
模型:封装应用程序的数据和业务逻辑POJO(Plain Old Java Object):数据模型
视图:实现应用程序的信息显示功能JSP、Freemarker等等
控制器:接收来自用户的输入,调用模型层,响应对应的视图组件Servlet Filter
2.使用Filter作为控制器的好处
使用一个过滤器来作为控制器,可以方便地在应用程序里对所有资源(包括静态资源)进行控制访问.
Servlet VS Filter
Servlet能做的Filter是否都可以完成?嗯。
Filter能做的Servlet都可以完成吗?
拦截资源却不是Servlet所擅长的! Filter中有一个FilterChain,这个API在Servlet中没有
3.使用范例
需求
代码(这里使用的是Servlet 3.0的注解的方式,不需要在web.xml中配置)
@WebFilter(filterName = "filterController", urlPatterns = "*.action")
public class FilterController implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
// Filter实现Servlet功能
String servletPath = #();
String path = null;
// 2.判断servletPath,若其等于"/product-input.action",则转发到
// /WEB-INF/pages/input.jsp
if ("/product-input.action".equals(servletPath)) {
path = "/WEB-INF/pages/input.jsp";
}
if ("/product-save.action".equals(servletPath)) {
String productName = request.getParameter("productName");
String productDesc = request.getParameter("productDesc");
BigDecimal productPrice = new BigDecimal(request.getParameter("productPrice"));
Product product = new Product(1001, productName, productDesc,
productPrice);
System.out.println("Save Product: " + product);
request.setAttribute("product", product);
path = "/WEB-INF/pages/details.jsp";
}
if (path != null) {
request.getRequestDispatcher(path).forward(request, response);
return;
}
chain.doFilter(request, response);
}
public void destroy() {}
public void init(FilterConfig fConfig) throws ServletException {}
}