As many have suggested its better to use Filters in this case.
Put following snippet into web.xml
Filter definition
<filter>
<filter-name>ProcessFilter</filter-name>
<filter-class>my.filter.ProcessFilter</filter-class>
</filter>
Filter mapping
<!-- Map all ".jsp" that should go through the filter-->
<filter-mapping>
<filter-name>ProcessFilter</filter-name>
<url-pattern>/content/*.jsp</url-pattern>
</filter-mapping>
<!-- If you have Any servlets that needs to go through ProcessFilter -->
<filter-mapping>
<filter-name>ProcessFilter</filter-name>
<servlet-name>MyServlet</servlet-name>
</filter-mapping>
OncePerRequestFilter
If you would want to execute the filter only once you could store an attribute in request scope for the first time, and next time you could check if the attribute is set in which case do not process further.
If you are using Spring framework you can either use one of the sub classes of OncePerRequestFilter
or extend it and just implement doFilterInternal()
.
Otherwise you could refer to OncePerRequestFilter.java
: raw and implement/extend your filter.
Here is a simplified version of it.
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) {
// Proceed without invoking this filter...
filterChain.doFilter(request, response);
}
else {
// Do invoke this filter...
request.setAttribute(alreadyFilteredAttributeName, Boolean.TRUE);
try {
doFilterInternal(httpRequest, httpResponse, filterChain);
}
finally {
// Remove the "already filtered" request attribute for this request.
request.removeAttribute(alreadyFilteredAttributeName);
}
}
}
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) {
throws ServletException, IOException
/*
*
*
* Put your processing logic here
*
*
*/
}
}