struts2使用Filter作为Control实现sevlet转发功能

来源:互联网 发布:nginx 自定义变量 编辑:程序博客网 时间:2024/06/10 00:15

使用Filter做为控制器,实现Servlet的功能


引言:传统的Filter我们一般用来检查做一些验证,但是今天我们将实现Servlet转发的功能。


简单回顾一下filter的开发步骤:


第一步:实现Filter接口


第二步:在web.xml配置文件中配置Filter的映射信息


主要源代码如下:



import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;


public class HelloWord implements Filter {


public void destroy() {

}


public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request =(HttpServletRequest) req;

//1、获取servletPath
String servletPath = request.getServletPath();
System.out.println(servletPath);
String path = null;
//2、判断servletPath,若其等于“product-input.action”则转发到//WEB-INF/pages/input.jsp
if(servletPath.equals("/product-input.action")){
path = "WEB-INF/pages/input.jsp";
}
//3、若其等于"/product-save.action",则
if(servletPath.equals("/product-save.action")){
//1.获取请求参数
String productName = request.getParameter("productName");
String productDesc = request.getParameter("productDesc");
String productPrice = request.getParameter("productPrice");

//2.把请求参数封装成一个product对象
Product product = new Product(null, productName, productDesc, Double.parseDouble(productPrice));
//3.执行保存操作
product.setId(1001);
//4.把product对象保存到request中,${param.productName}${requestScope.product.productName}
request.setAttribute("product", product);
path = "WEB-INF/pages/details.jsp";
}
if(path!=null){

//5.转发到指定页面
request.getRequestDispatcher(path).forward(req, resp);
return;
}
chain.doFilter(req, resp);

}


public void init(FilterConfig arg0) throws ServletException {

}

}

0 0
原创粉丝点击