基于Filter Dispatcher的Model2
虽然Servlet是Model2应用程序最常用的Controller,但也可以使用Filter作为Controller。
但是Filter无权充当欢迎页面。Structs2用Filter作为Controller。
JSP页面与Servlet Controller中一样;但它不是使用Servlet作为Controller,而是用了一个名为DispatcherFilter的类:
package com.gof.test.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.gof.test.action.SaveProductAction;
import com.gof.test.bean.Product;
import com.gof.test.bean.ProductForm;
public class DispatcherFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
String uri = ((HttpServletRequest)req).getRequestURI();
int lastIndex = uri.lastIndexOf("/");
String action = uri.substring(lastIndex + 1);
String dispatchUrlString = null;
if (action.equals("product_input")){
dispatchUrlString = "/jsp/controller/ProductForm.jsp";
}else
if (action.equals("product_save")){
ProductForm productForm = new ProductForm();
productForm.setName(req.getParameter("name"));
productForm.setDescription(req.getParameter("description"));
productForm.setPrice(req.getParameter("price"));
Product product = new Product();
product.setName(productForm.getName());
product.setDescription(productForm.getDescription());
try{
product.setPrice(Float.parseFloat(productForm.getPrice()));
}catch (NumberFormatException e){
e.printStackTrace();
}
SaveProductAction saveProductAction = new SaveProductAction();
saveProductAction.save(product);
req.setAttribute("product", product);
dispatchUrlString = "/jsp/controller/ProductDetails.jsp";
}
if (dispatchUrlString != null){
RequestDispatcher rDispatcher = req.getRequestDispatcher(dispatchUrlString);
rDispatcher.forward(req, resp);
}else{
chain.doFilter(req, resp);
}
}
public void destroy() {
// TODO Auto-generated method stub
}
}
在web.xml中注册这个Filter:
<!-- Filter -->
<filter>
<filter-name>dispatcherfilter</filter-name>
<filter-class>com.gof.test.filter.DispatcherFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>dispatcherfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
对于不是 product_input 和 product_save 的action,需要调用filterChain.doFilter()方法继续进行下面的流程。
在浏览器中访问之前的URL:
http://localhost:8080/base-webapp/product_input