Is it possible for the servlet filter to work, which servlet will handle the request

I am writing a filter that performs logging, and I need to disable this logging if the request completes on a specific servlet.

Is there a way for the filter to know which servlet will process the request?

+4
source share
3 answers

You might want to customize the display of the servlet filter so that it does not run in the case of requests for a specific servlet as a whole.

An example configuration might look like if you assume that there is one DefaultServlet that should not be affected by the filter and the other two servlets FirstServlet and SecondServlet that should 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> 
+6
source

You can assign a url template to be filtered for example

 <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 be run for each individual request processed by the servlet engine with a / admin mapping.

0
source

I always think that you should be able to make exceptions for url patterns in web.xml, for example. if you can 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 cannot help you like that!

Obviously, you have access to the URL in the filter through the request object so that you can 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(); } 

(hardcoded here, but you probably read it from the properties file), although this might not be useful to you, since you mentioned servlets in your request, not URL patterns.

EDIT: another thought. If you don't mind registering after the servlet finishes, you can 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 simply set this attribute to false.

 public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { req.setAttribute("DO_LOGGING", new Boolean(false)); // other stuff } 
0
source

Source: https://habr.com/ru/post/1346538/


All Articles