Name

<servlet-mapping>

Synopsis

Most containers support a special URI prefix (/servlet) that can invoke any servlet class the container has access to, for instance the URI /servlet/com.mycompany.MyServlet can be invoke the servlet class com.mycomapany.MyServlet. This isn’t mandated by the specification, however, so to make sure the application is portable, it’s better to map a unique path to a servlet instead. Explicit mapping also simplifies references between servlets and JSP pages, as described in Chapter 18. The <servlet-mapping> element is used for this purpose. The <servlet-name> subelement contains a name defined by a <servlet> element, and the <url-pattern> contains the pattern that should be mapped to the servlet (or JSP page):

<servlet-mapping>
  <servlet-name>purchase</servlet-name>
  <url-pattern>/po/*</url-pattern>
</servlet-mapping>
  
<servlet-mapping>
  <servlet-name>sales-report</servlet-name>
  <url-pattern>/report</url-pattern>
</servlet-mapping>
  
<servlet-mapping>
  <servlet-name>XMLProcessor</servlet-name>
  <url-pattern>*.xml</url-pattern>
</servlet-mapping>

A pattern can take one of four forms:

  • A path prefix pattern starts with a slash (/) and ends with /*, for instance /po/*.

  • An extension mapping pattern starts with *., for instance *.xml.

  • A default servlet pattern consists of just the / character.

  • All other patterns are exact match patterns.

When the container receives a request, it strips off the context path and then tries to find a pattern that matches a servlet mapping. ...

Get JavaServer Pages, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.