Servlet应用程序(2)----基于Filter Dispatcher的MVC

来源:互联网 发布:java selenium教程 编辑:程序博客网 时间:2024/05/23 20:03
    虽然Servlet是MVC中最常用的Controller,但也可以用过滤器作为Controller。不过注意,过滤器无权充当首页。只输入域名将不会调用过滤器的分发器。

例子:

public class DispatcherFilter implements Filter{    @Override    public void destroy() {        // TODO Auto-generated method stub    }    @Override    public void doFilter(ServletRequest request, ServletResponse response,            FilterChain filterChain) throws IOException, ServletException {        // TODO Auto-generated method stub        HttpServletRequest req = (HttpServletRequest) request;        String uri = req.getRequestURI();        int lastIndex = uri.lastIndexOf("/");        String action = uri.substring(lastIndex+1);        if(action.equals("product_input")){            //不处理        }else if(action.equals("product_save")){            //创建表单            ProductForm productForm = new ProductForm();            productForm.setName(request.getParameter("name"));            productForm.setDescription(request.getParameter("description"));            productForm.setPrice(request.getParameter("price"));            //创建模型            Product product = new Product();            product.setName(productForm.getName());            product.setDescription(productForm.getDescription());            product.setPrice(Float.parseFloat(productForm.getPrice()));            SaveProductAction saveProductAction = new SaveProductAction();            saveProductAction.save(product);            //保存模型到视图            request.setAttribute("product", product);        }        //映射到视图        String dispatchUrl = null;        if(action.equals("product_input")){            dispatchUrl="jsp/ProductForm.jsp";        }else if(action.equals("product_save")){            dispatchUrl="jsp/ProductDetails.jsp";        }        if(dispatchUrl != null){            RequestDispatcher rd = request.getRequestDispatcher(dispatchUrl);            rd.forward(request, response);        }else{            filterChain.doFilter(request, response);        }    }    @Override    public void init(FilterConfig filterConfig) throws ServletException {        // TODO Auto-generated method stub    }}

关于代码里提到的其他文件,请查看我的上一个博客。

部署:

    <filter>        <filter-name>DispatcherFilter</filter-name>        <filter-class>model2.DispatcherFilter</filter-class>    </filter>    <filter-mapping>        <filter-name>DispatcherFilter</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>

所得到的结果见上一个博客。不赘述。

阅读全文
0 0
原创粉丝点击