Deployment Descriptor:
In a Java web application, a file named web.xml is known as a deployment descriptor. It is an XML file and <web-app> is the root element for it. When a request comes web server uses a web.xml file to map the URL of the request to the specific code that handles the request.
Sample code of web.xml file:
<web-app> <servlet> <servlet-name>servletName</servlet-name> <servlet-class>servletClass</servlet-class> </servlet> <servlet-mapping> <servlet-name>servletName</servlet-name> <url-pattern>*.*</url-pattern> </servlet-mapping> </web-app>
How web.xml works:
When a request comes it is matched with the URL pattern in the servlet mapping attribute. In the above example, all URLs are mapped with the servlet. You can specify a URL pattern according to your needs. When the URL is matched with the URL pattern web server tries to find the servlet name in the servlet attributes same as in the servlet mapping attribute. When a match found control is goes to the associated servlet class.
Servlet “Hello World” example by extending the HttpServlet class.
HelloWorld.java
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; /** * This servlet program is used to print "Hello World" * on client browser using HttpServlet class. * @author W3schools360 */ public class HelloWorld extends HttpServlet { private static final long serialVersionUID = 1L; //no-argument constructor. public HelloWorld() { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("Hello World using HttpServlet class."); out.close(); } }
web.xml
<!--?xml version="1.0" encoding="UTF-8"?--> <web-app id="WebApp_ID" version="2.4" 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/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet> <servlet-name>HelloWorld</servlet-name> <servlet-class> com.w3schools.business.HelloWorld </servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping> </web-app>