Hello,
The Java Servlet specification version 2.3 introduced a new component type, called a filter. A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses. Filters typically do not themselves create responses, but instead provide universal functions that can be "attached" to any type of servlet or JSP page.
You can write your own filter to achieve this. Here is a small example directly taken from documentation which logs the servlet access.
public final class HitCounterFilter implements Filter
{
private FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig) throws ServletException
{
this.filterConfig = filterConfig;
}
public void destroy()
{
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
StringWriter sw = null;
PrintWriter writer = null;
if (filterConfig == null) return;
sw = new StringWriter();
writer = new PrintWriter(sw);
Counter counter = (Counter) filterConfig.getServletContext().getAttribute("hitCounter");
writer.println();
writer.println("===============");
writer.println("The number of hits is: " + counter.incCounter());
writer.println("===============");
writer.flush();
filterConfig.getServletContext().log(sw.getBuffer().toString());
...
chain.doFilter(request, wrapper);
...
}
}
This filter will be configured in
web.xml
as shown below
<filter id="filter_2">
<filter-name>activitylogger</filter-name>
<filter-class>com.yourcompany.filters.activity.HitCounterFilter</filter-class>
</filter>
Regards,