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.
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.
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.
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.
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.
<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>
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 are closed for "What is servlet mapping?".
this is an excellent guideline for servlet-mapping
please also give me more information
about jsp , java collection rmi
servlet-mapping definition is very nice tell me abt jsp
excellent…makes all things clear.
[…] the callback funtion we set the request url as the HelloWorld servlet. In web.xml we have done the servlet mapping for that […]
This site gives very simple explanations which are easy to understand
Good one Joe…
I am happy for this:what a great clarity.
I am dying for a Netbeans Struts2 + Spring + Hibernate + Tiles article that is as clear.
You have explained servlet mapping in a very simple way.
Keep it up.
“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?
Servlet mapping is defined in ________
servlet, web.xml, html, JSP
@yasir
The Servlet mapping is defined in Web.xml
you have defined Servlet mapping well.thanx
Lalit sharma on Feb 11th,2012
Thanks for providing valuable information, It clarifies a lot of confusion
good explanation
why jsp is static ? please explain it properly and servet is dynamic, please explain..
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.
Good One.I just asked one question in Interview.Is there different types of servlets available?.If so please tell me.
Ganesh
Nice
Good Explanation
explanation is very clear thanq
plz change background or words color
Very nice Joe , thanks .
very helpful. Thanku
Awesome explanation
good…
Good description
It is very useful for me…. Thanks Joe
Can we call destroy() method on servlets from service method?
How to use pattern like /test/*.do ?
It gives error…
Pls specify how to write Url-pattern..?? its confusing for me
Can u give different ideas of java coding which u r experienced while development.
very usefull
hi joe i dint understand servlet invoker?????can u explain me with example????????????
very nice Joe
it is such a helpful material
good information with simple way thanks….*
Nice dude…:)
Nice brother
not clearly define
Hi Joe
Can u just help me how to configure more than 1 servlet for a single application from in web.xml
@ 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
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…
good tutorial
Joe can you explain me how many xml file in a web application
ur site is very easy to understand
Good one
I don’t comment
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.
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
}
}
}
Excellent explanation and very clear
Excellent Sir I need Struct and Spring Explaination like tat.
Neat and clean explanation. very useful.
Thank u !!!
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.
superp explanatory on servlet mapping.I was satisfied with the content,to the expectation that i had when i started reading this page.
Good explanation.
Thank u !!!!
sooper
if there are two servlet mapping then which url pattern should i use in browser to display the contents.
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.
Kalakreenga joe…Good examples and easy to understand the concepts..Thanks buddy.
nice explanation sir……….
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??
ur explanation was simply super……keep going
Very nice explanation with good presentation
Web.xml
Basically their would be many types but we only read about generic servlet and HTTP servlet
nice work man.. helped a lot
Nice work. I spent hours for this information. Thanks again and appreciate your time.
Respected Sir,
I dont know how to set class path and run servlet program please guide me immediately
Anyone know how to deploy any servlet programe in weblogic10 server. If any then plz write procedure clearly
A good detailed explaination of servlet mapping
Thanks … It really helped a lot
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
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
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 ?
[…] web.xml primarily we are doing servlet mapping to give configuration for DispatcherServlet to load-on-startup and defining spring configuration […]
only 1 web.xml file
very nice explanation
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…
very good explanation about servlet mapping
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
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 ??
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 ?
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!!!
web.xml