Name

<servlet-mapping>

Synopsis

The <servlet-mapping> element maps a servlet or JSP page to a URL pattern.

Syntax

<servlet-mapping>
  <servlet-name>servletName</servlet-name>
  <url-pattern>urlPattern</url-pattern>
</servlet-mapping>

Most containers support a special URI prefix (/servlet) that can invoke any servlet class that the container has access to, for instance the URI /servlet/com.mycompany.MyServlet can 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 19. 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 ...

Get JavaServer Pages, 3rd 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.