What is servlet mapping?

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 added on 14/05/2008.

«

»

Comments on “What is servlet mapping?”

  1. nitin

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

  2. abcd

    servlet-mapping definition is very nice tell me abt jsp

    • Saurabh

      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. azhar

    excellent…makes all things clear.

  4. Rakman Rodrigues

    This site gives very simple explanations which are easy to understand

  5. Srikanth S

    Good one Joe…

  6. Tee

    I am happy for this:what a great clarity.

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

  7. ashwin

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

  8. peter

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

  9. yasir

    Servlet mapping is defined in ________

    servlet, web.xml, html, JSP

  10. Azam

    @yasir

    The Servlet mapping is defined in Web.xml

  11. Anonymous

    you have defined Servlet mapping well.thanx

    Lalit sharma on Feb 11th,2012

  12. Anonymous

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

  13. Raj

    good explanation

  14. sapan

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

  15. Karthikeyan p

    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.

  16. Ganesh

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

    Ganesh

  17. shankar

    Good Explanation

  18. explanation is very clear thanq

  19. saurabh

    plz change background or words color

  20. keerthi

    Very nice Joe , thanks .

  21. sarath

    very helpful. Thanku

  22. Anonymous

    Awesome explanation

  23. Anonymous

    Good description

  24. Mohanraj

    It is very useful for me…. Thanks Joe

  25. Anonymous

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

  26. Dhana

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

    It gives error…

  27. Harsh

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

  28. Chandu

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

  29. Anonymous

    very usefull

  30. vaibhav

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

  31. shuaib

    very nice Joe
    it is such a helpful material

  32. avdhesh samele

    good information with simple way thanks….*

  33. Deepak

    Nice dude…:)

  34. Khair

    Nice brother

  35. If u all guys have any doubt
    then HEAD FIRST’s SERVLET & JSP will be the BEST one

  36. Anonymous

    not clearly define

  37. sudip

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

  38. sudip

    @ 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

  39. divyesh shani

    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…

  40. shuaib muhammed p

    good tutorial

  41. Dipak Kumar

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

  42. Anonymous

    ur site is very easy to understand

  43. Raju Patil

    Good one

  44. Anonymous

    I don’t comment

  45. sainnni

    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.

  46. nadir ali

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

    • vivek

      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…

  47. Anonymous

    Excellent explanation and very clear

  48. Santhakumar

    Excellent Sir I need Struct and Spring Explaination like tat.

  49. Anonymous

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

  50. VTekale

    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.

  51. senthil_sss

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

  52. Naresh

    Good explanation.

    Thank u !!!!

  53. ss

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

  54. vijay

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

  55. Mahesh

    nice explanation sir……….

  56. Anonymous

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

  57. dev

    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

  58. shivani

    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

  59. Anonymous

    ur explanation was simply super……keep going

  60. suman

    Very nice explanation with good presentation

  61. Aman Arora

    nice work man.. helped a lot

  62. Nuwan

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

  63. Respected Sir,

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

  64. JYOTISH

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

  65. rajiv

    A good detailed explaination of servlet mapping

  66. Thanks … It really helped a lot

  67. Anonymous

    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

  68. satheesh

    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

  69. Vabbs

    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 ?

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

  71. boris

    very nice explanation

  72. megha

    very good explanation about servlet mapping

  73. Pal

    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.

    • Pal

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

      url-pattern –/upload

  74. muskaan

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

  75. mho938

    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 ?

  76. abc

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

  77. g.m

    whats the difference between these?

    /servlet

    and

    /servlet/*

    and

    /*

    and

    *.do

Your Comment