what happens when I configure a servlet before a filter in tomcat's web.xml?

有些话、适合烂在心里 提交于 2021-01-28 11:57:18

问题


In tomcat for a certain url, I want to skip all the filters and execute a servlet and I thought placing the servlet before the filter will to as I expected but still the filters behind the servlet mappings are executing. Am I doing anything wrong?

For instance, this is my web.xml


  <servlet>
        <servlet-name>APIRedirection</servlet-name>
        <servlet-class>com.test.APIRedirection</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>APIRedirection</servlet-name>
        <url-pattern>/abc/*</url-pattern>
    </servlet-mapping>

<filter>
        <filter-name>filter</filter-name>
        <filter-class>com.test.filter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

So when the incoming url contains "/abc/" I want my servlet to execute and skip the filters. I placed my servlet before all the filters but still the filters are getting executed when the incoming url contains '/abc/'.


回答1:


There is no concept of servlet before filter.

If servlets url mapping qualify filters url mapping then filter is executed before servlet.
I got your requirement you just don't want to hit Filters for certain urls.
a. If your application is still in starting phase, you can configure as given below

<servlet-mapping>
   <servlet-name>Servlet1</servlet-name>
   <url-pattern>/filtered/servlet1</url-pattern>
</servlet-mapping>

<servlet-mapping>
   <servlet-name>Servlet1</servlet-name>
   <url-pattern>/filtered/servlet2</url-pattern>
</servlet-mapping>

...
<filter-mapping>
    <filter-name>filter</filter-name>
    <url-pattern>/filtered/*</url-pattern>
</filter-mapping>

And the servlet url for which you want to bypass filter

<servlet-mapping>
   <servlet-name>Servlet1</servlet-name>
   <url-pattern>/unfiltered/servlet1</url-pattern>
</servlet-mapping>

2. If your application is already developed, and you configured a filter already with mapping /* then you can not skip that filter being executed. But you can add one more filter before that filter. Here filter order plays an important role,(reference for filter order) you can perform same functionality which you expected from a servlet. In your filter you just have to break filter chain and send response as given below

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,ServletException 
{
    //your business logic
    // construct responseToSend
    response.getOutputStream().write(responseToSend);
    return;
}

For more information of breaking filter chain refer this question



来源:https://stackoverflow.com/questions/56767940/what-happens-when-i-configure-a-servlet-before-a-filter-in-tomcats-web-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!