Java servlet Common Object Summary __java

Source: Internet
Author: User

I. Overview

A servlet is a Java program that executes on the server side and runs in a servlet container on the server side. To write a servlet, you need to implement the Javax.servlet.Servlet interface. JSP is the extension of the servlet, the first time the JSP runtime to be translated into Java code, translated into class files and that Java code is a servlet. There are servlet-api.jar,jsp-api.jar in Tomcat's Lib directory.

1. Servle Life Cycle Events

Object

Events

listener Interfaces and event classes

Web context
(See Access Web context)

Initializing and destroying

Javax.servlet.
Servletcontextlistener and

Servletcontextevent

Add, delete, or replace a property

Javax.servlet.
Servletcontextattributelistener and

Servletcontextattributeevent

Session
(see Maintaining Customer status)

Creation, expiration, and timeout

Javax.servlet.http.
Httpsessionlistener and

Httpsessionevent

Add, delete, or replace a property

Javax.servlet.http.
Httpsessionattributelistener and

Httpsessionbindingevent

2, Scope objects

Scope Objects

class

which components can access it

Web context

Javax.servlet.
ServletContext

Web Components in the Web context. See Access Web Context

Session

Javax.servlet.
http. HttpSession

A Web component that processes requests that belong to a session. See Maintaining client state.

Request

Javax.servlet.
ServletRequest

Subtype of

The Web component that handles the request.

Page

Javax.servlet.
Jsp. PageContext

Creates a JSP page for the object.

Second, JSP built-in objects

1, request, HttpServletRequest, it contains information about the browser request, and provides several for obtaining cookies,

header, and a useful method for session data.

2, Response, HttpServletResponse objects, and provides several methods for setting responses to the browser (such as cookies, headers, etc.)

3. The Out object is an instance of Javax.jsp.JspWriter and provides several methods that you can use to echo the output to the browser.

4, PageContext represents a Javax.servlet.jsp.PageContext object. It is an API for easy access to a wide range of namespaces, servlet-related objects, and a way of wrapping common servlet-related functionality.

5, the session represents a requested Javax.servlet.http.HttpSession object. Session can store user's state information

6, Applicaton represents a Javax.servle.ServletContext object. This helps you find information about the servlet engine and the servlet environment

7, config represents a Javax.servlet.ServletConfig object. This object is used to access the initialization parameters of the servlet instance.

8, page represents Javax.servlet.jsp.HttpJspPage, a servlet instance generated from the page.

Iii. ServletContext, Servletcontextlistener, servletcontextevent

The Servletcontextlistener interface, which listens to the lifecycle of the ServletContext object, is actually listening to the life cycle of the Web application. When the servlet container starts or terminates a Web application, the Servletcontextevent event is triggered, which is handled by Servletcontextlistener. Two methods for handling Servletcontextevent events are defined in the Servletcontextlistener interface. Contextinitialized (Servletcontextevent SCE): This method is called when the servlet container launches a Web application. After the method is called, the container initializes the filter, and initializes the servlet that needs to be initialized when the Web application is started. Contextdestroyed (Servletcontextevent SCE): This method is called when the servlet container terminates a Web application. Before this method is invoked, the container destroys all the servlet and filter filters first.

The following is an example to introduce the use of Servletcontextlistener. The Counterservlet class can only count the number of times a Web page has been accessed by the client after it has started. If you restart the Web application, the counter will again count the number of visits starting at 1. In practical applications, it is often necessary to count the number of pages accessed by the client since the Web application was published, which requires that when the Web application is terminated, the value of the counter is permanently stored in a file or database, and the initial value of the counter is read from the file or database when the Web application restarts. Then continue counting on this basis.

The ability to write or read a number of counters to a file can be done by a custom Myservletcontextlistener class (see routine 4-11), which has the following features:

Reads the counter's value from the file when the Web application starts, and stores the counter object that represents the counter in the Web application scope. The path to the file that holds the counter is helloapp/count/count.txt.

Saves the value of the counter in the Web application scope to the Count.txt file when the Web application terminates.

Routine 4-11 Myservletcontextlistener.java

public class Myservletcontextlistener implements servletcontextlistener{
public void contextinitialized (Servletcontextevent sce) {
System.out.println ("HelloApp application is initialized.");
  //Get ServletContext Object
ServletContext Context=sce.getservletcontext ();
  try{
To read a counter's numeric value from a file
BufferedReader reader=new BufferedReader (
New InputStreamReader (context.
getResourceAsStream ("/count/count.txt"));
int Count=integer.parseint (Reader.readline ());
Reader.close ();
  //Create counter objects
Counter counter=new Counter (count);
Save counter objects to Web application scope
Context.setattribute ("Counter", counter);
}catch (IOException e) {e.printstacktrace ();}
}
  public void contextdestroyed (Servletcontextevent sce) {
System.out.println ("HelloApp application is destroyed.");
  //Get ServletContext Object
ServletContext Context=sce.getservletcontext ();
  //Get Counter object from Web application range
Counter counter= (Counter) context.getattribute ("Counter");
  if (counter!=null) {
try{
Write the value of the counter in the Count.txt file
String Filepath=context.getrealpath ("/count");
filepath=filepath+ "/count.txt";
PrintWriter pw=new PrintWriter (filepath);
Pw.println (Counter.getcount ());
Pw.close ();
}catch (IOException e) {e.printstacktrace ();}
}
}
}
The user-defined Myservletcontextlistener listener only registers the servlet container first, and the servlet container invokes the associated method of the listener when it starts or terminates the Web application. The,<listener> element is used to register the listener with the container in the Web.xml file:
<listener>
<listener-class>mypack. Myservletcontextlistener<listener-class/>
</listener>

The following steps demonstrate the role of the Myservletcontextlistener listener.

(1) Create a count.txt file in the Helloapp/count directory, where a number "5" is stored in the file.

(2) Start Tomcat. In the browser , Counterservlet is accessed through Http://localhost:8080/helloapp/counter, and the browser-side display counter has a value of 5 for the first time the servlet is accessed.

(3) Refresh the above access to the Counterservlet page, you will see that every time the value of the counter is increased by 1, assuming that the last refresh of the counter after the value of 10.

(4) manual termination of HelloApp application. If you view the Helloapp/count/count.txt file, you will find that the number stored in the file changes to 10.

(5) Manually restart the HelloApp application. Counterservlet is accessed again in the browser, and when the servlet is first accessed, the browser-side display counter has a value of 10.

As can be seen from the above experiment, the Myservletcontextlistener Listener and Counterservlet share the counter object of the counter in the scope of the Web application. The listener manipulates the Counter object when the Web application starts or terminates, and the servlet manipulates the counter object each time it responds to a customer request.

Observe the order of the Myservletcontextlistener and the Lifeservlet of the name Lifeinit in the Tomcat console and find that when the Web application is started, The servlet container first invokes the Myservletcontextlistener contextinitialized () method, then invokes the Lifeinit init () method, and when the Web application terminates, The servlet container first invokes the Lifeinit destroy () method, and then calls the Myservletcontextlistener contextdestroyed () method. Thus, in the life cycle of the Web application, the ServletContext object was first created and later destroyed.

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.