Is it possible for a servlet filter to work out which servlet will handle the request
I'm writing a filter that performs logging and I nee开发者_如何学Pythond to disable this logging if the request is going to end up at a certain servlet.
Is there any way for the filter to know which servlet will handle the request?
You might want to setup servlet filter mapping to not fire it in case of requests for particular servlet altogether.
Example configuration could look like this assuming that there is one DefaultServlet that should not be impacted by filter and two other servlets FirstServlet and SecondServlet which have to be affected.
<filter-mapping>
<filter-name>MyFilter</filter-name>
<servlet-name>FirstServlet</servlet-name>
</filter-mapping>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<servlet-name>SecondServlet</servlet-name>
</filter-mapping>
You can assign url pattern which are to be filtered e.g.
<filter>
<filter-name>Admin</filter-name>
<filter-class>com.nil.FilterDemo.AdminFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Admin</filter-name>
<url-pattern>/admin/*</url-pattern>
</filter-mapping>
This filter will run for every single request handled by the servlet engine with /admin mapping.
I always think that you should be able to make exceptions to url-patterns in a web.xml e.g. if you could do something like this:
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>
<match>/resources/*</match>
<except>/resouces/images/blah.jpg</except>
</url-pattern>
but you can't so that's no help to you!
You obviously have access to the URL in the Filter through the request object so you could do something like this:
public void doFilter(ServletRequest sRequest, ServletResponse sResponse,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)sRequest;
if(!request.getRequestURI.equals("/resources/images/blah.jpg")) {
doLogging();
}
chain.doFilter();
}
(hard-coded here but you'd probably read it from a property file) although this may not be of use to you as you mentioned servlets in your query as opposed to URL patterns.
EDIT: another thought. If you don't mind doing your logging after the servlet has completed you could do something like this:
public void doFilter(ServletRequest sRequest, ServletResponse sResponse,
FilterChain chain) throws IOException, ServletException {
sRequest.setAttribute("DO_LOGGING", new Boolean(true));
chain.doFilter();
Boolean doLogging = (Boolean)sRequest.getAttribute("DO_LOGGING");
if(doLogging) {
doLogging();
}
}
and your servlet that you want to exclude from logging can just set that attribute to false.
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws IOException {
req.setAttribute("DO_LOGGING", new Boolean(false));
// other stuff
}
精彩评论