
Servlet mapping is a mapping which is defined in the web.xml file and it contains the mapping of a particular servlet to the corresponding url. It maps url patterns to servlets. When there is a request from a client, the servlet web container decides to which servlet it should forward to. Then context path of url is matched for mapping servlets.
To be precise, there should be a way to map a user url to a servlet so that it can be processed by that servlet.
web.xml is located inside the WEB-INF folder of the application. So it is not accessible by the user.
Web container accepts the user request and assigns it to the particular servlet by looking at the mapping file.
Servlet Mapping:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>SampleServlet</servlet-name>
<servlet-class>com.techfinance.project.ServletExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SampleServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
As per the above mapping, if the url pattern ends with “.do” then it would be handled by the servlet class ServletExample.
For example, url is http://locahost:8080/EmployeePortal/getEmp.do
But what would happen if the url ends with .dos?
We don’t have any servlet configured to handle this type of url. So the web container can decide which servlet which should be assigned to service that request or we can configure a default servlet in the web.xml file.
Also multiple servlets can be configured in the web.xml file for diff kind of requests. Kindly check below.
<web-app>
<servlet>
<servlet-name>SampleServlet</servlet-name>
<servlet-class>com.techfinance.project.ServletExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SampleServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>SampleServlet1</servlet-name>
<servlet-class>com.techfinance.project.ServletExample1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SampleServlet1</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>SampleServlet2</servlet-name>
<servlet-class>com.techfinance.project.ServletExample2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SampleServlet2</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>