程序员代码改变世界

1. 使用Filter 作为控制器

2016-11-28  本文已影响157人  MPPC

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

1. MVC 设计模式概览

2. 使用 Filter 作为控制器的好处

3. 使用范例

@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 {}
}
上一篇下一篇

猜你喜欢

热点阅读