The Java web servlet technology

Source: Internet
Author: User

1. servlet Basics

For servlet technology development, Sun offers a number of column interfaces and classes, The most important of these is the Javax.servlet.Servlet interface, where the two important packages are javax.servlet and Javax.servlet.http,servlet, a class that implements the Servlet interface, which is made up of a web container (Tomcat /jetty, etc.) is responsible for invoking and creating, for receiving and responding to user requests. 5 abstract methods are defined in a servlet interface:

Method Function
void init (servletconfig config)

In charge of the servlet initialization, the container calls this method after the Servlet object is created. The method accepts a

The ServletConfig class parameter that the servlet container uses to pass configuration information to the servlet

ServletConfig Getservletconfig () Returns the ServletConfig object passed when the container calls init (servletconfig config)
void Service (ServletRequest req, servletresponse Res)

This method is called when a request to the Servlet object is received by the client in response to a request from the user.

The container constructs a servletrequest and Servletresponse object to be passed into the method as a parameter.

In this method, the request information is obtained through the ServletRequest object, and after the request processing is completed, the

Servletresponse Object Setting Response message

String Getservletinfo ()

Returns a string that contains the servlet information. Note that the method itself needs to be redefined in Genericservlet

The method in the class returns an empty string

void Destroy () Responsible for releasing the resources occupied by the Servlet object, which the container calls when the Servlet object is destroyed

The servlet top-level class structure looks like this:

2. The first servlet program

Create a new Java Web project, and then create a new Hello class, Hello.java source code is as follows:

Package Zzz;import Java.io.ioexception;import Java.io.printwriter;import javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class Hello extends HttpServlet {    @Override public    void doget (HttpServletRequest request, httpservletresponse response) throws IOException {        //Set Response message encoding        response.setcontenttype ("Text/html;charset=utf-8");        PrintWriter out = Response.getwriter ();        Out.println ("Hello World");    }        @Override public    void DoPost (HttpServletRequest request, httpservletresponse response) throws IOException {        This.doget (request, response);}    }

The configuration file Web. XML is as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"     xmlns= "Http://xmlns.jcp.org/xml/ns/javaee"     xsi:schemalocation= "Http://xmlns.jcp.org/xml/ns/javaee http ://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd "id=" webapp_id "version=" 3.1 ">    <display-name>zzz< /display-name>  <servlet> <!--register Servlet---      <servlet-name>Hello</servlet-name> <!--Specify the servlet name      ---<servlet-class>zzz. hello</servlet-class> <!--specify servlet full class name--  </servlet>  <servlet-mapping> <!-- Map servlet External Access path-      <servlet-name>Hello</servlet-name> <!--specify servlet name--      < url-pattern>/hello</url-pattern> <!--Specify the virtual path to access the servlet--  </servlet-mapping></ Web-app>

The startup run browser appears as follows:

3. servlet life cycle

The servlet life cycle is broadly divided into 3 phases, the initialization phase, the run phase, and the destruction phase. Here is a detailed description of each stage:

    • Initialization phase: When a client makes a request to the servlet container to access the servlet, the container first parses the request, checks to see if there is a Servlet object in memory, if it is used directly, otherwise creates the Servlet object, and then calls the Init () method, noting that The entire declaration cycle of the servlet, Init () will only be called once
    • Run phase: This is the most important stage of the servlet, which constructs a servletrequest and Servletresponse object as parameters passed into the servlet's service () method. For each access to the servlet, the servlet container invokes the service () method, and the service () method is called multiple times throughout the servlet's life cycle
    • Destroy phase: When the server shuts down or the Web application is removed from the container, it goes to this stage, and the Destroy () method is called, and the Destroy () method is called only once for the entire life cycle

When the client accesses the servlet for the first time, the container creates the Servlet object, but sometimes it wants the Servlet object to follow startup when Tomcat starts. At this point, you only need to use the <load-on-startup> element in Web. XML, the sample configuration is as follows:

<servlet>      <servlet-name>Hello</servlet-name>      <servlet-class>zzz. Hello</servlet-class>    <!--automatically load servlet programs--    <load-on-startup>1</load-on-startup >   </servlet>  <servlet-mapping>      <servlet-name>Hello</servlet-name>      <url-pattern>/hello</url-pattern>  </servlet-mapping>
4, ServletConfig and Servletcontextservletconfig interface

During servlet runtime, if you need some ancillary information, such as file encoding, company using servlet, etc., this information can be configured with the <init-param> element in Web. XML, and when Tomcat Initializes a servlet, The servlet configuration information is encapsulated into a ServletConfig object passed to the servlet via init (servletconfig config). ServletConfig defines a series of methods for obtaining configuration information:

Method Function
String Getservletname () Returns the servlet name, which is the value in <servlet-name> in Web. xml
ServletContext Getservletcontext () Returns the ServletContext object representing the current web app
String Getinitparameter (string name) Returns the corresponding parameter value based on the parameter name if no return null is found
Enumeration<string> Getinitparameternames () Returns a enumeration object that contains all the initialization parameters

Next, take Getinitparameter () as an example to illustrate the use of the method:

The Web. XML configuration file is as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"     xmlns= "Http://xmlns.jcp.org/xml/ns/javaee"     xsi:schemalocation= "Http://xmlns.jcp.org/xml/ns/javaee http ://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd "id=" webapp_id "version=" 3.1 ">    <display-name>zzz< /display-name>  <servlet>      <servlet-name>Hello</servlet-name>      <servlet-class >zzz. hello</servlet-class>      <init-param>          <param-name>company</param-name>          < param-value>dahua</param-value>      </init-param>  </servlet>  < servlet-mapping>      <servlet-name>Hello</servlet-name>      <url-pattern>/hello</ Url-pattern>  </servlet-mapping></web-app>

The Hello.java file is as follows:

Package Zzz;import Java.io.ioexception;import Java.io.printwriter;import javax.servlet.servletconfig;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class Hello extends HttpServlet {    @Override public    void Doget ( HttpServletRequest request, HttpServletResponse response) throws IOException {        //Set Response message encoding        Response.setcontenttype ("Text/html;charset=utf-8");        PrintWriter out = Response.getwriter ();                ServletConfig config = This.getservletconfig ();        String param = Config.getinitparameter ("Company");        Out.println ("Company:" + param);    }        @Override public    void DoPost (HttpServletRequest request, httpservletresponse response) throws IOException {        This.doget (request, response);}    }
ServletContext interface

When the servlet container is started, a unique ServletContext object is created for each web app that represents the current web app, which encapsulates all the information about the Web app and enables data sharing between multiple Servlet objects. In Web. XML, you can configure not only the initialization information of the servlet, but also the initialization information for the entire Web application, as shown in the following configuration:

<context-param>    <param-name>name</param-name>    <param-value>luoxn28</ Param-value></context-param><context-param>    <param-name>company</param-name>    <param-value>dahua</param-value></context-param>

Note: There can only be one <param-name> and <param-value> in a <context-param> element; The above configuration is configured in Web. XML <web-app> below. The Hello.java file is as follows:

Package Zzz;import Java.io.ioexception;import Java.io.printwriter;import java.util.enumeration;import Javax.servlet.servletcontext;import Javax.servlet.http.httpservlet;import javax.servlet.http.HttpServletRequest; Import Javax.servlet.http.httpservletresponse;public class Hello extends HttpServlet {@Override public void doget (H Ttpservletrequest request, HttpServletResponse response) throws IOException {//Set Response message encoding Response.setconten        Ttype ("Text/html;charset=utf-8");                PrintWriter out = Response.getwriter ();        ServletContext context = This.getservletcontext ();        enumeration<string> paramnames = Context.getinitparameternames ();            while (Paramnames.hasmoreelements ()) {String name = Paramnames.nextelement ();            String value = context.getinitparameter (name);        OUT.PRINTLN (name + ":" + value + "<br/>"); }} @Override public void DoPost (HttpServletRequest request, HttpServletResponse Response) throws IOException {This.doget (request, response); }}

Because all servlets in a web App share a ServletContext object, the domain properties of the ServletContext object can be accessed by all servlets in the Web App. The ServletContext interface defines the 4 methods for adding, deleting, and setting ServletContext domain properties, respectively:

Method Function
Object getattribute (String name) Gets a matching domain property value according to the specified parameter
Enumeration<string> Getattributenames () Returns a enumeration object that contains all the domain property names stored in the ServletContext
void SetAttribute (String name, Object object) Set ServletContext domain property value, name-domain property name, object-domain property value
void RemoveAttribute (String name) Removes a domain property from ServletContext based on the specified domain property name

Through the above method can realize the sharing of data between multiple servlets, this specific example does not post code, the online can refer to a lot of information, such as can click Javaweb Learning Summary (vi)--servlet development (b).

The Java web servlet technology

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.