简体   繁体   中英

Tomcat 9+: overriding Servlet mapping using @WebServlet annotation

Which is the precedence order of @WebServlet annotation vs web.xml servlet mapping? More specifically we've a use case where we would rather not modify the web.xml but would need to override one of the servlet mappings. Our web.xml has something like:

<servlet>
   <servlet-name>foo</servlet-name>
   <servlet-class>com.whatever.simple.foo</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>foo</servlet-name>
   <url-pattern>/foo/*</url-pattern>
</servlet-mapping>

And we are considering overriding this using:

@WebServlet("/foo/*")
public class OurCustomImplementation extends HttpServlet {
}

So the question is:

  • is the specification allowing us to add some parameter to do so (eg override or prioriry parameters)?
  • is the specification guaranting that our class will always override web.xml ?
  • Will Tomcat 9+ allow to do it, even if maybe using some extensions?

Both Servlet 3.1 Final and 4.0.Final specs say in 12.2 Specification of Mappings:

If the effective web.xml (after merging information from fragments and annotations) contains any url-patterns that are mapped to multiple servlets then the deployment must fail.

So the spec clearly doesn't allow this.

Alternative solution: create a WebFilter that does a forward dispatch to another url, that your overriding servlet handles. Or just do your thing in the filter itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM