1. 使用Filter 作为控制器

最近整理一下学习笔记,并且准备放到自己的博客上。也顺便把Struts2 复习一遍

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 = httpRequest.getServletPath();
		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 {}
}
人生如棋,我愿为为卒;行走虽慢,可曾见我后退一步!
原文地址:https://www.cnblogs.com/MPPC/p/6104326.html