Customize Servlet URL

This tutorial is an additional work of the previous lab. It allows a Servlet can be accessed by different URLs.

  1. Open the servletlabs project in the previous tutorial.
  2. Create a file: web.xml in the WebContent→WEB-INF folder
  3. Insert the following code into the web.xml file:

    <web-app>
        <servlet>
                  <servlet-name>HelloServ</servlet-name>
                  <servlet-class>first.servlet.HelloWorld</servlet-class>
         </servlet>
         <servlet-mapping>
                 <servlet-name>HelloServ</servlet-name>
                 <url-pattern>/helloworld</url-pattern>
         </servlet-mapping>
         <servlet-mapping>
                 <servlet-name>HelloServ</servlet-name>
                 <url-pattern>/hello_world</url-pattern>
         </servlet-mapping>
    </web-app>
  4. The tag <servlet-name> defines your servlet; <servlet-class> points to the class that implements the servlet and <servlet-mapping> declares the mapping between your servlet with different URLs.
  5. Save the file.
  6. Right click on the servletlabs project, select Run As→Run on Server. Finish.
  7. Select Restart server. Finish.
  8. Now, the “HelloWorld” servlet can be accessed by different URLs:

Exercises

  1. Add another mapping to allow your servlet can be accessed by the URL: http://localhost:8080/servletlabs/[whatever you type here].