The life cycle of the servlet + how it is implemented

Source: Internet
Author: User

1.Servlet life cycle:
(1) was created:
By default, the servlet is created by the server the first time it is accessed. The init () method is called.
A servlet will only be created once. The init () method is only called once.
The servlet is a singleton. While the server is multithreaded. There may be a thread safety issue.
To avoid security issues, try not to define member variables in the servlet. Even if it is defined. Do not do anything else (query only).

You can configure a servlet to be created when you start the server
Configure startup creation
Value:
0 and positive integers: created at server startup
The smaller the number, the higher the priority.
Negative integers:-1 is the default value. Created the first time it is accessed
<load-on-startup>2</load-on-startup>

(2) Provision of services:
Each time it is accessed, the service method is invoked to provide services. Called multiple times.
Services Provided:
1. Get the request message data
2. Setting the response message data

(3) Be destroyed:
The servlet is destroyed when the server shuts down.

The servlet is destroyed before the server shuts down normally, and the Destory () method is called before it is destroyed. Called only once.


the 2.Servlet implementation method:
(1) Implement the Servlet interface:
* Servletconfig:servlet Configuration Object
* Getinitparameter (String name): Gets the initialization parameter value of the servlet
* Enumeration Getinitparameternames (): Gets the name of the initialization parameter of the Servlet enumeration
* ServletContext Getservletcontext (): Get ServletContext
* String getservletname (): Gets the servlet name

* Created by the server.
* For the implementation of Getservletconfig ().
1. Define member variables. ServletConfig Config
2. Assigning values in the Init method
3. Return the member variable in Getservletconfig ().

(2) Inheritance Genericservlet:
Optimization 1: For the implementation of Getservletconfig ().
In this class, the Init method has two, one is a parameter, and the other is a non-parametric one. We're going to make a copy without a reference.

Optimization 2: Implements the ServletConfig interface
We can get the ServletContext object in a simple way.


(3) Inheritance HttpServlet: Encapsulation of HTTP protocol.
1. How to get the request
String method = Req.getmethod ();
2. Perform different actions depending on the mode
if ("GET". Equals (method)) {
Get the code of the way
Doget (REQ,RESP);
}else if ("POST". Equals (method)) {
Get the code of the way
DoPost (REQ,RESP);
}

Later we need to replicate doget () and DoPost ();

Code Demo:

1 Importjava.io.IOException;2 3 ImportJavax.servlet.Servlet;4 ImportJavax.servlet.ServletConfig;5 Importjavax.servlet.ServletException;6 Importjavax.servlet.ServletRequest;7 ImportJavax.servlet.ServletResponse;8 9 Ten  Public classServlettestImplementsServlet { One  A     /** - * Initialize method. Called after the servlet is created, called once -      */ the      Public voidInit (servletconfig config)throwsservletexception { -  -System.out.println ("Init () is called ... "); -     } +  -     /** + * methods to get ServletConfig objects A      */ at      PublicServletConfig Getservletconfig () { -         //TODO auto-generated Method Stub -         return NULL; -     } -  -     /** in * Method of providing service, call multiple times -      */ to      Public voidService (ServletRequest req, servletresponse Res) +             throwsservletexception, IOException { -  the Res.setcontenttype (Getservletinfo ()); *String IP =req.getremoteaddr (); $System.out.println (REQ.GETREMOTEADDR () + "Ah, how is it visited?!" ");Panax Notoginseng         if("192.168.1.65". Equals (IP)) { -Res.getwriter (). Write ("); the             return; +         } ARes.getwriter (). Write ("); the          +     } -  $     /** $ * Method of obtaining servlet information. such as: Version number, author, etc. -      */ -      PublicString Getservletinfo () { the         //TODO auto-generated Method Stub -         return NULL;Wuyi     } the  -     /** Wu * Destroy method call once.  -      */ About      Public voiddestroy () { $  -System.out.println ("Destroy () to hang up ..."); -     } -  A  +}

XML file:

1 <?XML version= "1.0" encoding= "UTF-8"?>2 <Web-appversion= "2.5" 3 xmlns= "Http://java.sun.com/xml/ns/javaee" 4 Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee6 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd ">7   8    <servlet>9         <Servlet-name>One</Servlet-name>Ten         <Servlet-class>Serlet.servlettest</Servlet-class>     One     <Load-on-startup>5</Load-on-startup> A     </servlet> -     <servlet-mapping> -         <Servlet-name>One</Servlet-name> the         <Url-pattern>/one</Url-pattern> -     </servlet-mapping> -  -   <Display-name></Display-name>     +   <welcome-file-list> -     <Welcome-file>index.jsp</Welcome-file> +   </welcome-file-list> A </Web-app>

The life cycle of the servlet + how it is implemented

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.