What is servlet mapping?

Last modified on September 11th, 2014 by Joe.

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.

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!

Comments on "What is servlet mapping?"

  1. nitin says:

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

  2. abcd says:

    servlet-mapping definition is very nice tell me abt jsp

  3. azhar says:

    excellent…makes all things clear.

  4. […] the callback funtion we set the request url as the HelloWorld servlet. In web.xml we have done the servlet mapping for that […]

  5. Rakman Rodrigues says:

    This site gives very simple explanations which are easy to understand

  6. Srikanth S says:

    Good one Joe…

  7. Tee says:

    I am happy for this:what a great clarity.

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

  8. ashwin says:

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

  9. peter says:

    “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?

  10. yasir says:

    Servlet mapping is defined in ________

    servlet, web.xml, html, JSP

  11. Azam says:

    @yasir

    The Servlet mapping is defined in Web.xml

  12. Anonymous says:

    you have defined Servlet mapping well.thanx

    Lalit sharma on Feb 11th,2012

  13. Anonymous says:

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

  14. Raj says:

    good explanation

  15. sapan says:

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

  16. Karthikeyan p says:

    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.

  17. Ganesh says:

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

    Ganesh

  18. Amrapali says:

    Nice

  19. shankar says:

    Good Explanation

  20. baasha says:

    explanation is very clear thanq

  21. saurabh says:

    plz change background or words color

  22. keerthi says:

    Very nice Joe , thanks .

  23. sarath says:

    very helpful. Thanku

  24. Anonymous says:

    Awesome explanation

  25. sumit says:

    good…

  26. Anonymous says:

    Good description

  27. Mohanraj says:

    It is very useful for me…. Thanks Joe

  28. Anonymous says:

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

  29. Dhana says:

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

    It gives error…

  30. Harsh says:

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

  31. Chandu says:

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

  32. Anonymous says:

    very usefull

  33. vaibhav says:

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

  34. shuaib says:

    very nice Joe
    it is such a helpful material

  35. avdhesh samele says:

    good information with simple way thanks….*

  36. Deepak says:

    Nice dude…:)

  37. Khair says:

    Nice brother

  38. Anonymous says:

    not clearly define

  39. sudip says:

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

  40. sudip says:

    @ 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

  41. divyesh shani says:

    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…

  42. shuaib muhammed p says:

    good tutorial

  43. Dipak Kumar says:

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

  44. Anonymous says:

    ur site is very easy to understand

  45. Raju Patil says:

    Good one

  46. Anonymous says:

    I don’t comment

  47. sainnni says:

    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.

  48. nadir ali says:

    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
    }
    }
    }

  49. Anonymous says:

    Excellent explanation and very clear

  50. Santhakumar says:

    Excellent Sir I need Struct and Spring Explaination like tat.

  51. Anonymous says:

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

  52. VTekale says:

    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.

  53. senthil_sss says:

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

  54. Naresh says:

    Good explanation.

    Thank u !!!!

  55. aaa says:

    sooper

  56. ss says:

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

  57. Saurabh says:

    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.

  58. vijay says:

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

  59. Mahesh says:

    nice explanation sir……….

  60. Anonymous says:

    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??

  61. Anonymous says:

    ur explanation was simply super……keep going

  62. suman says:

    Very nice explanation with good presentation

  63. Aman Arora says:

    Web.xml

  64. Aman Arora says:

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

  65. Aman Arora says:

    nice work man.. helped a lot

  66. Nuwan says:

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

  67. G.Palanikumar says:

    Respected Sir,

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

  68. JYOTISH says:

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

  69. rajiv says:

    A good detailed explaination of servlet mapping

  70. Kholofeloo says:

    Thanks … It really helped a lot

  71. Anonymous says:

    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

  72. satheesh says:

    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

  73. Vabbs says:

    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 ?

  74. […] web.xml primarily we are doing servlet mapping to give configuration for DispatcherServlet to load-on-startup and defining spring configuration […]

  75. Anonymous says:

    only 1 web.xml file

  76. boris says:

    very nice explanation

  77. vivek says:

    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…

  78. megha says:

    very good explanation about servlet mapping

  79. Pal says:

    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.

  80. Pal says:

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

    url-pattern –/upload

  81. muskaan says:

    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 ??

  82. mho938 says:

    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 ?

  83. abc says:

    i have tried running a java servlet which was deployed with web.xml,then the index.jsp was employed to create the webpage.But when it was run on the NETBEANS IDE it is not automatically invoking the webpage on browser .moreover it has been taking the localhost:8080/WebApplication1 where WebApplication1 is the project name.how does this need to be sorted?? pls help!!!

  84. prabu says:

    web.xml

Comments are closed for "What is servlet mapping?".