Java Web Programming servlet Technical detailed _java

Source: Internet
Author: User
Tags java web tomcat

How much do you know about the servlet technology of Java Web programming?

1, the Servlet Foundation
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 two important packages are javax.servlet and Javax.servlet.http,servlet, a class that implements the Servlet interface, which is created by the Web container (Tomcat /jetty, etc.) is called and created to receive and respond to user requests. 5 abstract methods are defined in the Servlet interface:

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 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 the servlet complete 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 start of the Run browser appears as follows:

3. servlet lifecycle

The servlet lifecycle is roughly divided into 3 phases, the initialization phase, the runtime phase, and the destruction phase . The following 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 resolves the request 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 In the entire declaration cycle of the servlet, Init () calls only once
Run Phase: This is the most important phase of the servlet, which constructs a servletrequest and Servletresponse object to be passed as a parameter to the servlet's service () method. For every visit to the servlet, the servlet container invokes a service () method, and the service () method is invoked multiple times throughout the servlet lifecycle
Destroy phase: When the server shuts down or the Web application is removed from the container, the Destroy () method is invoked and the Destroy () method is invoked only once for the entire lifecycle.
When the client first accesses the servlet, the container creates the Servlet object, but sometimes you want the Servlet object to follow the startup when Tomcat starts, how do you handle it? 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 the servlet program-->
 <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 ServletContext

ServletConfig interface
During a servlet run, if you need some ancillary information, such as file encoding, a company that uses a servlet, and so on, this information can be configured in Web.xml using the <init-param> element, and when Tomcat Initializes a servlet, Encapsulates the servlet configuration information into a ServletConfig object passed through init (servletconfig config) to the servlet. ServletConfig defines a series of methods for obtaining configuration information:

Next, take Getinitparameter () as an example to explain the use of this 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>

Hello.java files are 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 Res
  Ponse) 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.D
 Oget (request, response); }
} 

ServletContext interface
When the servlet container is started, a unique ServletContext object representing the current Web application is created for each Web application, which encapsulates all the information about the Web application and implements data sharing among multiple Servlet objects. In Web.xml, you can configure not only the initialization information for 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 be only one <param-name> and <param-value> in a <context-param> element, and the above configuration is in Web.xml <web-app > Configuration. Hello.java files are 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 (HttpServletRequest request, HttpServletResponse Res
  Ponse) throws IOException {//Set Response message encoding Response.setcontenttype ("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 {thi S.doget (request, response);
 }
}

 

Because all servlet in a Web application shares a ServletContext object, the domain properties of the ServletContext object can be accessed by all servlet in the Web application. 4 Methods for adding, deleting, and setting ServletContext field properties are defined in the ServletContext interface:

Through the above methods can be implemented to share data between multiple servlet, this specific example does not paste code, the Internet can refer to a lot of information, such as can be clicked:

Summary of development of Javaweb servlet (II.)

This is all in this article and I want to help you understand the Java Web's servlet technology.

Resources

1, "Introduction to Java Web application Development" servlet Technical Chapter

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.