web.xml Servlet mapping

Servlet mapping using web.xml file?

Explanation

URL mapping for servlets:


Servlets are preferred methods to handle requests, so are many web applications use servlets with JSP. So to use servlets effectively in JSP pages url mapping is done. We use "<servlet-class>" inside the "<servlet>" tag to specify the a servlet class which is invoke using the url in "<url-pattern>" tag.

Example :


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>User</servlet-name>
<servlet-class>User</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>User</servlet-name>
<url-pattern>/User</url-pattern>
</servlet-mapping>
</web-app>

In the above example the url "/User" invokes the servlet "User".

URL mapping for JSP pages:


URL mapping can also be done for JSP pages using the "<servlet>" tag. In the "<jsp-file>" tag one can specify the JSP file and in the "<url-pattern>" tag the url used to display the jsp page is specified.

Example :


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>registration.jsp</servlet-name>
<jsp-file>/registration.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>registration.jsp</servlet-name>
<url-pattern>/registration.xml</url-pattern>
</servlet-mapping>

In the above example the url "/registration.xml" invokes the file "/registration.jsp" without any redirection.

Ask Questions

Ask Question