10

I encountered a J2EE project written by others. When I come to the web.xml, there are two different servlets mapped on the same URL pattern. I wonder the purpose of this approach. How exactly does that work and what's the puspose?

Here is the relevant part of the web.xml:

<servlet>
    <servlet-name>fileDownload</servlet-name>
    <servlet-class>com.htsoft.core.web.servlet.FileDownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>fileDownload</servlet-name>
    <url-pattern>/file-download</url-pattern>
</servlet-mapping>

<servlet>
    <servlet-name>fileDownLoad</servlet-name>
    <servlet-class>com.kaiwii.oa.action.system.FileDownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>fileDownLoad</servlet-name>
    <url-pattern>/file-downLoad</url-pattern>
</servlet-mapping>  
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
kaiwii ho
  • 1,367
  • 7
  • 21
  • 40

1 Answers1

15

Only one servlet will get called; there's no mechanism I'm aware of for handling a single request with two servlets (nor am I sure what that would even mean).

Servlet URL patterns may overlap, but having two with the exact same URL doesn't make sense. I don't recall if the servlet spec explicitly disallows it, however matching stops at the first matching. The matching method is defined in the spec.

Servlet 2.4 spec PDF See p. 85+

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • The spec is pretty clear that the url-patterns must be tested in order of their occurrence, so the first longest match holds. SRV 2.5. – user207421 Oct 25 '11 at 07:14
  • @EJP I thought that's what the mapping specifications portion did? – Dave Newton Oct 25 '11 at 07:15
  • I amended my comment, but the parts that discuss filter mappings and security constraints are explicit about web.xml order; #11.1 that discusses isn't. – user207421 Oct 25 '11 at 07:18
  • @EJP Yeah, the spec *implies* it, but... you know how well *that* works out. – Dave Newton Oct 25 '11 at 07:19
  • 1
    Exactly. It's a curious omission given how much work has taken place on it over more than ten years. – user207421 Oct 25 '11 at 07:26
  • I haven't find in this spec that "url-patterns must be tested in order of their occurrence", also @WebServlet annotation doesn't have "priority" param. – Mladen Adamovic Sep 13 '16 at 09:37
  • What I've found in Servlet 3.0 spec: "The last filter in this chain is the last matching filter in the deployment descriptor for this request URI. The last filter in this chain is the filter that invokes the first filter in the matching chain, or invokes the target Web resource if there are none. " It's not very clear to me what they meant. – Mladen Adamovic Sep 13 '16 at 09:45
  • @MladenAdamovic No surprise there, although I haven't verified this. – Dave Newton Sep 13 '16 at 10:32