The previous article delves into the workings of the servlet, which we implement to build a Web application for the servlet.
Enter the following text: 1. Using Web.xml to configure the servlet is the most common and easiest way to do this.
<! 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>
<display-name>archetype Created web application</ display-name>
<servlet>
<servlet-name>servlet's name (custom) </servlet-name>
< Servlet-class>servlet class name (full path, such as Com.taobao.Servlet) </servlet-class>
<load-on-startup>1</ load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>servlet's name ( Consistent with above) </servlet-name>
<url-pattern> mapping path (such as:/login) </url-pattern>
</ Servlet-mapping>
</web-app>
2. Use Java programming to configure the boot servlet.
we have to implement the class Servletcontextlistener because this class listens for the initialization of the servlet, so we can register the servlet in its Contextinitialized method ( Not only the servlet, we can also register listeners, and filters.
package Indi.jack.chapter1.ServletCotext;
Import javax.servlet.FilterRegistration.Dynamic;
Import Javax.servlet.Servlet;
Import Javax.servlet.ServletContext;
Import javax.servlet.ServletContextEvent;
Import Javax.servlet.ServletContextListener;
Import javax.servlet.ServletRegistration;
Import Javax.servlet.annotation.WebListener; /** * <p>Title:ServletStartup</p> * <p>Description:</p> * <p>Company:</p> * @autho
R Jackhoo * @date March 5, 2017 morning 10:12:01 * * @WebListener public class Servletstartup implements servletcontextlistener{ @Override public void contextdestroyed (Servletcontextevent arg0) {} @Override public void contextinitialized (Servletcontextevent arg0)
{ServletContext context=arg0.getservletcontext ();
Servletregistration myservlet=context.addservlet ("Hello", "Indi.jack.chapter1.Servlet.HelloServlet");
Myservlet.addmapping ("/hello"); SYSTEM.OUT.PRINTLN ("Manual registration Servlet complete.")
"); }
}
3. Attach Source code address
GitHub Project Address