Reputation:
Is there a way to call a method()
after each doPost(req, res)
without having to rewrite method()
at the end of each doPost
block in every single servlet?
Upvotes: 2
Views: 1001
Reputation: 85789
Just to add to the answer of JeremiahOrr, you must also verify that you're performing a POST request on your servlet, otherwise the code will also be executed for other requests like GET. This would be a more concrete example:
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
}
}
Upvotes: 1
Reputation: 2630
The easiest way is probably using a 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
}
You'll then need to set up filter
and filter-mapping
in your web.xml. If you're using a Servlet 3.x container (like Tomcat 7+), you can use annotations.
Upvotes: 3