We can map url pattern with servlet class at web.xml.
Following example will illustrate this.
Project directory structure is as below:
index.jsp
1 2 3 4 5 6 7 8 9 10 11 12 | <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>Configuration using web.xml </h1> <a href="welcome1">Show Welcome1</a> </body> </html> |
web.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" 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_3_0.xsd"> <display-name>Servlet Tutorial 1</display-name> <description> This is a simple web application. To map url with srvlet class at web.xml </description> <servlet> <servlet-name>welcome</servlet-name> <servlet-class>ebhor.servlet.Welcome1</servlet-class> </servlet> <servlet-mapping> <servlet-name>welcome</servlet-name> <url-pattern>/welcome1</url-pattern> </servlet-mapping> </web-app> |
Welcome1.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | package ebhor.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Welcome1 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet Welcome1</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet Welcome1 </h1>"); out.println("</body>"); out.println("</html>"); } finally { out.close(); } } } |
In web.xml url pattern(welcome1) will match to a logical name(welcome) that logical name is matched with servlet fully qualified class name(ebhor.servlet.Welcome1).
Result: