What is servlet mapping?

14/05/2008

Servlet mapping specifies the web container of which java servlet should be invoked for a url given by client. It maps url patterns to servlets. When there is a request from a client, servlet container decides to which application it should forward to. Then context path of url is matched for mapping servlets.

How is servlet mapping defined?

Servlets should be registered with servlet container. For that, you should add entries in web deployment descriptor web.xml. It is located in WEB-INF directory of the web application.
Entries to be done in web.xml for servlet-mapping:

<servlet-mapping>
<servlet-name>milk</servlet-name>
<url-pattern>/drink/*</url-pattern>
</servlet-mapping>

servlet-mapping has two child tags, url-pattern and servlet-name. url-pattern specifies the type of urls for which, the servlet given in servlet-name should be called. Be aware that, the container will use case-sensitive for string comparisons for servlet matching.

Syntax for servlet mapping as per servlet specification SRV.11.2:

A string beginning with a ‘/’ character and ending with a ‘/*’ suffix is used for path mapping.
A string beginning with a ‘*.’ prefix is used as an extension mapping.
A string containing only the ‘/’ character indicates the “default” servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
All other strings are used for exact matches only.

Rule for URL path mapping:

It is used in the following order. First successful match is used with no further attempts.

1. The container will try to find an exact match of the path of the request to the path of the servlet. A successful match selects the servlet.
2. The container will recursively try to match the longest path-prefix. This is done by stepping down the path tree a directory at a time, using the ’/’ character as a path separator. The longest match determines the servlet selected.
3. If the last segment in the URL path contains an extension (e.g. .jsp), the servlet container will try to match a servlet that handles requests for the extension. An extension is defined as the part of the last segment after the last ’.’ character.
4. If neither of the previous three rules result in a servlet match, the container will attempt to serve content appropriate for the resource requested. If a “default” servlet is defined for the application, it will be used.

Ads by Google

What is implicit mapping?

A servlet container can have a internal JSP container. In such case, *.jsp extension is mapped to the internal container. This mapping is called implicit mapping. This implicit mapping allows ondemand execution of JSP pages. Servlt mapping defined in web application has high precedence over the implicit mapping.

Example code for java servlet mapping:

<servlet>
<servlet-name>milk</servlet-name>
<servlet-class>com.javapapers.Milk</servlet-class>
</servlet>
<servlet>
<servlet-name>points</servlet-name>
<servlet-class>com.javapapers.Points</servlet-class>
</servlet>
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>com.javapapers.ControllerServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>milk</servlet-name>
<url-pattern>/drink/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>points</servlet-name>
<url-pattern>/pointlist</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

What is Servlet Invoker?

As defined by Apache Tomcat specification, the purpose of Invoker Servlet is to allow a web application to dynamically register new servlet definitions that correspond with a <servlet> element in the /WEB-INF/web.xml deployment descriptor.By enabling servlet invoker the servlet mapping need not be specified for servlets. Servlet ‘invoker’ is used to dispatch servlets by class name.

Enabling the servlet invoker can create a security hole in web application. Because, Any servlet in classpath even also inside a .jar could be invoked directly. The application will also become not portable. Still if you want to enable the servlet invoker consult the web server documentation, because every server has a different method to do it.

In Tomcat 3.x, by default the servlet invoker is enabled. Just place the servlets inside /servlet/ directory and access it by using a fully qualified name like http://[domain]:[port]/[context]/servlet/[servlet.
This mapping is available in web application descriptor (web.xml), located under $TOMCAT_HOME/conf.

/servlet/ is removed from Servlet 2.3 specifications.
In Tomcat 4.x, by defaul the servlet invoker id disabled. The <servlet-mapping> tag is commented inside the default web application descriptor (web.xml), located under $CATALINA_HOME/conf. To enable the invoker servlet uncomment the following two blocks.

<!– The mapping for the invoker servlet –>
<!–
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
–>


<!–
<servlet>
<servlet-name>invoker</servlet-name>
<servlet-class>
org.apache.catalina.servlets.InvokerServlet
</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
–>

Good luck for all your servlet mappings!

This Servlet tutorial was posted on 14/05/2008.
Ads by Google

87 comments on “What is servlet mapping?

  1. this is an excellent guideline for servlet-mapping
    please also give me more information
    about jsp , java collection rmi

  2. servlet-mapping definition is very nice tell me abt jsp

    • JSP stands for Java Server Pages.It is a implementation of Servlet and reduce the writing cost of html under the out.println in the servlet. it reduces the work overhead of software programmer.

  3. Pingback: Getting Started with AJAX using Java

  4. This site gives very simple explanations which are easy to understand

  5. I am happy for this:what a great clarity.

    I am dying for a Netbeans Struts2 + Spring + Hibernate + Tiles article that is as clear.

  6. You have explained servlet mapping in a very simple way.
    Keep it up.

  7. “If the last segment in the URL path contains an extension (e.g. .jsp), the servlet container will try to match a servlet that handles requests for the extension.”

    How does a container know whether a servlet handles an extension?

  8. Servlet mapping is defined in ________

    servlet, web.xml, html, JSP

  9. @yasir

    The Servlet mapping is defined in Web.xml

  10. you have defined Servlet mapping well.thanx

    Lalit sharma on Feb 11th,2012

  11. Thanks for providing valuable information, It clarifies a lot of confusion

  12. why jsp is static ? please explain it properly and servet is dynamic, please explain..

  13. Thanks for your ground level explanation.
    Please tell What happened (Means how the control will flow) in a same URL is mapped for a servlet and a Filter in web.xml.

  14. Good One.I just asked one question in Interview.Is there different types of servlets available?.If so please tell me.

    Ganesh

    • Basically their would be many types but we only read about generic servlet and HTTP servlet

  15. It is very useful for me…. Thanks Joe

  16. Can we call destroy() method on servlets from service method?

  17. How to use pattern like /test/*.do ?

    It gives error…

  18. Pls specify how to write Url-pattern..?? its confusing for me

  19. Pingback: jQuery AJAX to call Java method | Easy jQuery | Free Popular Tips Tricks Plugins API Javascript and Themes

  20. Can u give different ideas of java coding which u r experienced while development.

  21. hi joe i dint understand servlet invoker?????can u explain me with example????????????

  22. very nice Joe
    it is such a helpful material

  23. good information with simple way thanks….*

  24. Hi Joe
    Can u just help me how to configure more than 1 servlet for a single application from in web.xml

  25. @ sapan
    See servlet is a simple java file which can be configured from web.xml and the parameters involved in the servlet are capable enough to accept dynamic data where as .jsp file is based on html and dynamic configuration is not really acceptable and another fore most thing is that jsp will have the view part contents not the business logic inside thus its is said to be jsp is a static kind of file

  26. can i remove all my xml files from my web applicatin?? and replace them with json???
    i am using netbeans IDE. i want to totally remove XMLs and use only json…

  27. Joe can you explain me how many xml file in a web application

  28. Hi Joe,
    I am new to this blog but I find it fascinating.
    It would be great help if u post a detailed article on URL Rewriting ..how to manually rewrite and how it helps in saving the session.
    Also I have a query that is do multiple browsers running the same web app simultaneously share the same session..coz they return the same sessionid.

  29. sir i have made simple proogram of servelet but it is not running
    web.wml is

    HelloWorld Application

    This is a simple web application with a source code organization
    based on the recommendations of the Application Developer’s Guide.

    Hello
    uk

    Hello
    /hello

    class name is uk

    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;

    public class uk extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {

    // Set the response MIME type of the response message
    response.setContentType(“text/html”);
    // Allocate a output writer to write the response message into the network socket
    PrintWriter out = response.getWriter();

    // Write the response message, in an HTML page
    try {
    out.println(“”);
    out.println(“Hello, World”);
    out.println(“”);
    out.println(“Hello, world!”); // says Hello
    // Echo client’s request information
    out.println(“Request URI: ” + request.getRequestURI() + “”);
    out.println(“Protocol: ” + request.getProtocol() + “”);
    out.println(“PathInfo: ” + request.getPathInfo() + “”);
    out.println(“Remote Address: ” + request.getRemoteAddr() + “”);
    // Generate a random number upon each request
    out.println(“A Random Number: ” + Math.random() + ““);
    out.println(“”);
    } finally {
    out.close(); // Always close the output writer
    }
    }
    }

    • it’s web.xml not .wml….to use Math class import java.util.*;

      web.xml is not included by default anymore if u are using any IDE, ex:- eclipse.You will need to explicitly specify the ide to create it.IDE’s this days go for annotations instead…

  30. Excellent Sir I need Struct and Spring Explaination like tat.

  31. Neat and clean explanation. very useful.
    Thank u !!!

  32. It is very useful article. I created simple servlet application, but when i try http://localhost:8080/SomeServlet it gives me error- HTTP status 404. SomeServlet is my folder name in web-apps.

    plz help me.

  33. superp explanatory on servlet mapping.I was satisfied with the content,to the expectation that i had when i started reading this page.

  34. if there are two servlet mapping then which url pattern should i use in browser to display the contents.

  35. Kalakreenga joe…Good examples and easy to understand the concepts..Thanks buddy.

  36. hi all,

    what happens if com.javapapers.Milk java file is not found in the path specified ????

    will we get noclassdeffound error or something else??

  37. hi joe sir,
    i want to go from
    index.jsp(href) to hello.jsp
    can u give me answer request comes from where and go to where.
    is this 1 to 2 to 3 to 4
    or 3 to 1 to 2 to 4

    1.my web.xml have
    *.html

    2.my dispatcher-servelet.xml have

    3. my index.jsp have
    Hello World

    4. my jsp name is hello.jsp

  38. hi joe sir,
    i want to go from
    index.jsp(href) to hello.jsp
    can u give me answer request comes from where and go to where.
    is this 1 to 2 to 3 to 4
    or 3 to 1 to 2 to 4

    1.my web.xml have
    *.html

    2.my dispatcher-servelet.xml have

    3. my index.jsp have
    Hello World

    4. my jsp name is hello.jsp

  39. ur explanation was simply super……keep going

  40. Very nice explanation with good presentation

  41. Nice work. I spent hours for this information. Thanks again and appreciate your time.

  42. Respected Sir,

    I dont know how to set class path and run servlet program please guide me immediately

  43. Anyone know how to deploy any servlet programe in weblogic10 server. If any then plz write procedure clearly

  44. A good detailed explaination of servlet mapping

  45. i have two servlets my first servlet name Loginservlet.java my second servlet name viewservlet.java, in my login.jsp page i gave action as LoginServlet.do and in web.xml i declare url pattern as *.do for second servlet i.e for viewservlet what action i can give view.jsp and what url pattern i can give in web.xml help me …i understood how to call multiple servltes in web.xml but i don no to declare the url path….bec in some url path they gave*.do in some they gave/pointlist/ in some they gave/milk/* then hoe i can give in jsp with my servlet name

  46. Hi Palani,

    this is the format for setting classpath

    set Classpath= C:\Program files\apzch software Foundation\Tomcat5.0\webapps\servlets.example\WEB-INF\classes

    if u want some more details means post it..

    if i know let u know

  47. I am using eclipse. It generates Servlet with annotation “@WebServlet”. I commented out this annotation and mapped a web.xml.

    When I provided the servlet class name as URL pattern, it worked fine.

    But when I changed URL pattern in web.xml and matched the “action” in html file, It gives me a 404 error.

    What is the correct procedure to change the URL pattern ?

  48. Pingback: Spring MVC Hello World

  49. could you help me to implement personal chat application using direct web remoting

  50. very good explanation about servlet mapping

  51. I’m making a file uploader in gwt. The java file has a upload widget where in
    FileUpload upload=new FileUpload();
    upload.setAction(“upload”)
    Later in web.xml file:

    UploadServlet
    com.gwt.dlogpackage.client.UploadServlet

    UploadServlet
    /upload

    The servlet file that extends HTTPServlet is UploadServlet.java.
    Is there any error in the above web.xml file? As I am not getting the file uploaded.

    • servlet-name — UploadServlet
      servlet-class — com.gwt.dlogpackage.client.UploadServlet

      url-pattern –/upload

  52. type: Exception report

    message: Class SignUp is not a Servlet

    description: The server encountered an internal error that prevented it from fulfilling this request.
    How can I remove this error ??

  53. i have a android aplication that have two edittext for get parameter to login
    and in my server code i have a registeri
    how i can pass edittext parameter into my server ?

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>