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

最佳答案

只是要添加到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
    }
}

关于java - doPost完成后运行方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22461362/

10-10 09:19