Java:servlet (create,lifecycle, interactive, tomcat file analysis)

Source: Internet
Author: User
Tags naming convention

1.Servlet:A servlet (server Applet) is the abbreviation for a Java servlet, a server-side program written in Java for a small service program or service connector, with the primary function of interactively browsing and modifying data to generate dynamic Web content. The narrow-sense servlet refers to the Java language implementation of an interface, the generalized servlet refers to any implementation of the Servlet interface class, in general, people will understand the servlet as the latter. The servlet runs in a Java-enabled application server. In principle, servlets can respond to any type of request, but in most cases the servlet is used only to extend the HTTP protocol-based Web server. The first to support the servlet standard was JavaSoft Java Web server, after which some other Java-based Web servers began to support the standard servlet. 2.MyEclipse Create servlet: first create a Web project project:              then click Next until this interface, generate Web. XML Deployment Descriptor selected (internally created to form a Web. XML document), click Finish           To Create a servlet class:   
 PackageCn.zzsxt.lee.servlet;Importjava.io.IOException;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;/*** @description servlet is also an ordinary Java class that inherits HttpServlet. What is a non-trivial servlet? -->java class * used in HTTP protocol, what is the transfer of data? Processing requests sent by clients *@authorSeven Lee * @date July 17, 2017 pm 4:20:30 * * servlet life cycle: (singleton) (!!) IMPORTANT) * 1. Load and instantiate (create Servlet object) * 2. Initialize (init) (called only once, when the servlet is accessed for the first time) * 3. Process client requests and respond (service) * 4. Automatic destruction (Destroy) (also only Called once, which is called after a normal shutdown) **/ Public classFirstservletextendsHttpServlet {//connect the database, store the user's information in the data, and return the user for storage success@Override Public voidInit ()throwsservletexception {//The init method is called only once, and is called when the first access servletSystem.out.println ("I am the Init method, I was called"); } @Overrideprotected voidService (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {//The service method is called every time a request is sent//request--> Request: Handling requests sent to the server by the client//response--> response: After processing the request, respond to the client (404, 500 ...) if successfulSystem.out.println ("I am the service method, I was called"); //set the encoding formatRequest.getrequestdispatcher ("index.jsp"). Forward (request, response); } @Override Public voiddestroy () {//The destroy method will only be called once//When the server shuts down, when the client closes the connection, when all client requests are processed (normal shutdown), it is not called when the shutdown is not normal .System.out.println ("I was destroy method, I was called up"); }}

To modify the Web. XML Document:

<?XML version= "1.0" encoding= "UTF-8"?><Web-appXmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xmlns= "Http://java.sun.com/xml/ns/javaee"xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"ID= "webapp_id"version= "3.0">    <Display-name>First_servlet</Display-name>    <servlet>        <Servlet-name>Servlet</Servlet-name><!--Servlet-name is discretionary, without any restrictions, the naming convention also follows the Java Hump naming convention -        <Servlet-class>Cn.zzsxt.lee.servlet.FirstServlet</Servlet-class>    </servlet>    <servlet-mapping>        <Servlet-name>Servlet</Servlet-name><!--servlet-mapping servlet-name to be identical with <servlet> -        <!--<url-pattern>/reg</url-pattern>--><!--is to access the servlet's path, only through this path can access the servlet -        <Url-pattern>*.aaa</Url-pattern><!--match servlet in AAA end -        <!--<url-pattern>/ccc/*</url-pattern>--><!--match the servlet with the CCC start -        <Url-pattern>/*</Url-pattern><!--all paths must be intercepted by the servlet. -    </servlet-mapping>    <welcome-file-list>        <Welcome-file>index.jsp</Welcome-file>    </welcome-file-list>    </Web-app>

localhost:8080/Project name: View index.jsp

localhost:8080/Project name/reg (various access methods): Transfer data to the backend console by accessing the Web page

3.Servlet Life Cycle:

A: Load servlet loading is typically done when the Tomcat container is run, when the Servlet class is loaded into Tomcat, or when the client sends a request. The Web container is responsible for loading the servlet, and when the Web container starts or when the servlet is first used, the container is responsible for creating the servlet instance, but the user must pass The deployment descriptor (Web. xml) Specifies the location of the servlet, the name of the class in which the servlet resides, and, after successful loading, it instantiates the servlet in a reflective manner.    B: Initialize when a servlet is initialized, the container initializes the object by calling the Init () method, which is initialized to allow the servlet to do some initialization work before processing the client request, such as establishing a database connection, reading resource file information, etc., if initialization fails, The second servlet will be uninstalled directly. C: Enter the service  when a request is submitted, the servlet invokes the service () method for processing, often by invoking the doget () or Dopost () method on the request type, and in the Service () method, Servlets can accept customer requests through servletrequest, or they can use Servletresponse to set up response information.    D: Destruction the Destroy () method is automatically called when the Web container shuts down or detects that a servlet is being removed from the container, so that the instance frees up the resources it consumes. E: Uninstall when a servlet finishes calling the Destroy () method, the secondary instance waits to be reclaimed by the garbage collector, and the init () method initialization is called again if the servlet needs to be reused again.   Note:  under normal circumstances, the servlet is initialized only once, and the processing service is called multiple times, and the destruction is only called once, but if a servlet is not used for a long time, it is automatically destroyed by the container, and if it needs to be reused again, the operation will be initialized again. That is, in special cases, initialization may occur more than once, and destruction may occur more than once.  for the Service () method, this method generally does not need to be rewritten, because in HttpServlet there is already a good implementation, it will call the Doget (), the DoPost () method according to the request, that is, service () is used to turn, So we generally write a servlet that only needs to rewrite doget () or Dopost (). If you override the service () method, the Servlet container will give the request to this method, and if you override the service () method without calling Doxxx (), even if you rewrite the other doget () in the servlet, DoPost () And so will not be called, because the servlet service () is automatically called (Just like the Init () and Destory () methods), so if you need to rewrite the service () method for some reason, and call Dopost () according to different method , the Doget () method, it is necessary to add a sentence at the end of Super.service (), so that the problem can be solved. 4. Interactive: 5.Tomcat file Analysis:

Java:servlet (create,lifecycle, interactive, tomcat file analysis)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.