How do I use servlet aliasing, so the URL "http://foo.com/mywebapp/servlet/a.b.c.MyServlet" can become "http://foo.com/mywebapp/Thingy"?

Alex Chaffee

According to the Servlet 2.2 spec, you can set a servlet alias in the WEB-INF/web.xml deployment descriptor for your webapp.

The <servlet-name> element defines the "canonical name" for the servlet. This name is used to refer to the servlet elsewhere in the file.

The <servlet-mapping> element defines a mapping from a URL pattern to a servlet. This element contains two sub-elements, <servlet-name> and <url-pattern>.

For example:

<servlet>
 <servlet-name>hello</servlet-name>
 <servlet-class>com.stinky.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
 <servlet-name>hello</servlet-name>
 <url-pattern>hi</url-pattern>
</servlet-mapping>
in the webapp "examples" would map the URL http://www.stinky.com/examples/hi to the servlet com.stinky.HelloWorld.

The url-pattern can contain the wildcard character "*". For instance, Tomcat maps all JSPs to the JspServlet using


    <servlet>
        <servlet-name>jsp</servlet-name>
        <servlet-class>org.apache.jasper.runtime.JspServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>jsp</servlet-name>
        <url-pattern>*.jsp</url-pattern>
    </servlet-mapping>
The url-pattern can also map entire paths to a single servlet; the url-pattern "/catalog/*" would match a URL like "http://www.stinky.com/examples/catalog/furniture/couches/futon". The servlet can access the extra path info (past "catalog/") via the Request object using the getPathInfo() method.

If your server does not support the Servlet 2.2 API, then it usually provides an alternate method. Please submit feedback to tell how your favorite servlet engine does it!

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact