Reputation: 3134
I have a Spring MVC project and a spring rest project. In both cases, I'm using a filter to add a session ID for SLF4J/Logback logging. However, the filter is getting called for every HTTP request like static files, favicon.ico etc. I know this is happening because I'm using /* in filters. How to prevent this ? I want filter to be called for only for paths handled by my controllers. Here is my filter set in web.xml
<filter>
<filter-name>AppRequestFilter</filter-name>
<filter-class>com.company.appui.filter.AppRequestFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AppRequestFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
another app where I'm configuring filter in java program
private void registerFilters(Environment environment, ApplicationContext context) {
environment.addFilter(context.getBean(AppRequestFilter.class), "/*");
environment.addFilter(context.getBean(AuthFilter.class), "/*");
}
Sample URL for my spring rest project
localhost:8080/v1/apphealthcheck/epp?token=37e11b48119d
Sample URL for spring MVC project
localhost:28082/app-ui/index.html
- home page
localhost:28082/app-ui/login
- for ajax call from index.html
Upvotes: 0
Views: 1895
Reputation: 6608
You can specify comma separated values in url-pattern
or even use multiple url-pattern elements in
filter-mapping`. But for that to work, you need to have common prefix in your MVC controller URLs and REST URLs.
Now you can have the following mappings in web.xml
<filter-mapping>
<filter-name>myFilter</filter-name>
<url-pattern>/app/*,/v1/healthcheck/*</url-pattern>
</filter-mapping>
or
<filter-mapping>
<filter-name>myFilter</filter-name>
<url-pattern>/app/*</url-pattern>
<url-pattern>/v1/healthcheck/*</url-pattern>
</filter-mapping>
Upvotes: 1
Reputation: 455
You could've solved this by adding a specific URL path branch for all controller handled requests at the beginning and mapping the filter to that URL. Is it too late to refactor? Restful services are usually flexible this way while in development...
Upvotes: 1