As many of them suggested it is better to use filters in this case.
Put the following snippet in web.xml
Filter definition
<filter> <filter-name>ProcessFilter</filter-name> <filter-class>my.filter.ProcessFilter</filter-class> </filter>
Filter display
<filter-mapping> <filter-name>ProcessFilter</filter-name> <url-pattern>/content/*.jsp</url-pattern> </filter-mapping> <filter-mapping> <filter-name>ProcessFilter</filter-name> <servlet-name>MyServlet</servlet-name> </filter-mapping>
OncePerRequestFilter
If you want to execute the filter only after the first time you can save the attribute in the request area, and the next time you can check whether the attribute is set, in this case it is not processed further.
If you use the Spring framework, you can use one of the OncePerRequestFilter subclasses or extend it and just implement doFilterInternal() .
Otherwise, you can refer to OncePerRequestFilter.java : raw and implement / extend your filter.
Here is a simplified version.
public class ProcessFilter extends Filter { public final void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) { throw new ServletException("OncePerRequestFilter just supports HTTP requests"); } HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String alreadyFilteredAttributeName = "ALREADY_PROCESSED_BY_PROCESS_FILTER"; if (request.getAttribute(alreadyFilteredAttributeName) != null) {
source share