doPost完成后运行方法

时间:2014-03-17 17:37:28

标签: java servlets

有没有办法在每个method()之后调用doPost(req, res),而不必在每个servlet的每个method()块的末尾重写doPost

2 个答案:

答案 0 :(得分:3)

最简单的方法可能是使用servlet Filter。

public class YourFilter implements Filter {
  public void init(FilterConfig filterConfig)  throws ServletException { }
  public void destroy() { }

  public void doFilter(ServletRequest request, ServletResponse response, 
      FilterChain chain) throws IOException, ServletException {

    // whatever you want to do before doPost

    chain.doFilter(request, wrapper);

    // whatever you want to do after doPost
}

然后,您需要设置filterfilter-mapping in your web.xml。如果您正在使用Servlet 3.x容器(如Tomcat 7+),则可以use annotations

答案 1 :(得分:2)

只需添加JeremiahOrr的答案,您还必须验证您是否在servlet上执行了POST请求,否则代码也将执行其他请求(如GET)。这将是一个更具体的例子:

public class YourFilter implements Filter {
    public void init(FilterConfig filterConfig)  throws ServletException { }
    public void destroy() { }

    public void doFilter(ServletRequest request, ServletResponse response, 
        FilterChain chain) throws IOException, ServletException {
        // whatever you want to do before doPost
        chain.doFilter(request, wrapper);
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        if(httpRequest.getMethod().equalsIgnoreCase("POST")) {
            //whatever you want to do after doPost only HERE
        }
        //whatever you want to do after doGet, doPost, doPut and others HERE
    }
}