Warm tip: This article is reproduced from serverfault.com, please click

Tomcat 9+: overriding Servlet mapping using @WebServlet annotation

发布于 2020-12-03 14:25:34

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 (e.g. 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?
Questioner
Simone Avogadro
Viewed
1
Vsevolod Golovanov 2021-01-13 00:00:56

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.