ServletContext is used by the Servlet program to communicate with the Web Container. such as writing logs, forwarding Requests. Each Web application contains a context that is shared by individual programs within the Web Application.
Because context can be used to save resources and share, the biggest application I know of ServletContext is that the Web cache----to read infrequently changed content into memory, so the server responds to the requested
There is no need for slow disk i/o. Servletcontextlistener is a listener for servletcontext, if ServletContext changes, such as when the server starts
ServletContext is created and ServletContext will be destroyed when the server shuts Down. In the JSP file, application is an instance of servletcontext, created by default by the JSP Container.
The Getservletcontext () method is called in the Servlet to get an instance of Servletcontext.
The idea that we use caching is probably:
When the server starts, the Servletcontextlistener contextinitialized () method is called, so the cache is created Inside. Cache content can be read from the file or from the database
Generate the class, using the Ervletcontext.setattribute () method to save the cache class in an instance of Servletcontext.
The program uses Servletcontext.getattribute () to read the Cache. If it is a JSP, use a pplication.getattribute (). If it is a Servlet, use
Getservletcontext (). getattribute (). If the cache changes (such as the access count), you can change both the cache and the File/database. Or you can wait for a change to accumulate to a certain program and then save it.
Save it in the next Step.
The Servletcontextlistener contextdestroyed () method is called when the server is about to close, so the cached changes are saved Inside. Save the changed cache back to a file or database, and
The new original Content.
Import User; My own class
Import databasemanager; My own class
Import javax.servlet.ServletContext;
Import javax.servlet.ServletContextListener;
public class Mycontextlistener
Implements Servletcontextlistener {
Private ServletContext context = null;
public void contextinitialized (servletcontextevent Event) {
context = Event.getservletcontext ();
User user = Databasemanager.getuserbyid (1);
Context.setattribute ("user1", user);
}
public void contextdestroyed (servletcontextevent Event) {
User user = (user) context.getattribute ("user1"); Databasemanager.updateuserdata (user);
This.context = null;
}
}
Deployment Servletcontextlistener
You implement (implements) after Servletcontextlistener compiled, put it in the correct web-inf/classes directory, change the Web-inf directory under the Web. XML file, in web-
Add <listener> in App node
<listener-class>MyServletContextListener</listener-class>
</listener>
The following example is very good!!!
There is a Servletcontextlistener interface in the Servlet API that listens to the life cycle of a servletcontext object, and in effect listens to the life cycle of a Web Application. When
When a Servlet container starts or terminates a Web app, the Servletcontextevent event is triggered, and the event is handled by Servletcontextlistener. In the Servletcontextlistener interface
Defines two methods for handling servletcontextevent Events.
L contextinitialized (servletcontextevent sce): This method is called when the servlet container launches the Web app. After the method is called, the container initializes the filter and
Those servlets that need to be initialized when the Web app is started are Initialized.
L contextdestroyed (servletcontextevent sce): This method is called when the servlet container terminates the Web app. Before the method is called, the container destroys all servlets and
Filter Filters.
Here are two specific examples to illustrate the use of servletcontextlistener.
Example one: when the service starts, the data in the database is loaded into memory and assigned to a property name, and other servlets can access the property value through Getattribute. Have the following two
A step: the 1:servletcontext object is a shared memory for the entire web application, and any request can access the content inside
2: How to implement the content when the service starts up dynamically: What we need to do is:
1) implement the Servletcontextlisterner interface and commit to the memory via the SetAttribute (name,data) method;
2) the application project takes the data through GetAttribute (name).
Package servletcontexttest;
Import java.sql.Connection;
Import java.sql.PreparedStatement;
Import java.sql.ResultSet;
Import java.util.HashMap;
Import java.util.Map;
Import javax.servlet.ServletContext;
Import javax.servlet.ServletContextEvent;
Import javax.servlet.ServletContextListener;
Import Util. connecttool;
public class Servletcontextltest implements servletcontextlistener{
Implement the Destroy function within
public void contextdestroyed (servletcontextevent Sce) {System.out.println ("this is the last destroyeed");
}
Implement the initialization function, which is triggered when an event occurs
public void contextinitialized (servletcontextevent Sce) {
ServletContext Sct=sce.getservletcontext ();
map<integer,string> depts=new hashmap<integer,string> ();
Connection connection=null;
PreparedStatement pstm=null;
ResultSet rs=null;
try{
Connection=connecttool.getconnection ();
String sql= "select deptno,dname from dept"; Pstm=connection.preparestatement (sql);
Rs=pstm.executequery ();
While (rs.next ()) {
Depts.put (rs.getint (1), rs.getstring (2));
}
Store the value you have taken into a property key-value pair
Sct.setattribute ("dept", depts);
System.out.println ("======listener test is beginning=========");
}catch (Exception E) {
E.printstacktrace ();
}finally{
CONNECTTOOL.RELEASERSC (rs, pstm, connection);
}
}
}
After the above coding is completed, the following configuration is still required in Web. XML to make the listener Work. <listener>
<listener-class>ServletContextTest.ServletContextLTest</listener-class>
</listener> Upon completion of the above configuration, the Web server will load the listener directly when it is started and can access the data through the following Applications.
Package servletcontexttest; Import java.io.IOException;
Import java.io.PrintWriter;
Import java.util.*;
Import javax.servlet.ServletContext;
Import javax.servlet.ServletException;
Import javax.servlet.http.HttpServlet;
Import javax.servlet.http.HttpServletRequest;
Import javax.servlet.http.HttpServletResponse;
public class Createemployee extends httpservlet{
@Override
protected void service (httpservletrequest request, httpservletresponse Response)
Throws servletexception, IOException {
ServletContext sct=getservletconfig (). Getservletcontext ();
Get property values from a context environment by property name
Map<integer,string> Dept (map<integer,string>) Sct.getattribute ("dept");
Set<integer> Key=dept.keyset ();
Response.setcontenttype ("text/html;charset=utf-8");
PrintWriter Out=response.getwriter ();
Out.println ("
Out.println ("<body>");
Out.println ("<form action= '/register ' action= ' post ' >");
Out.println ("<table alignb= ' center ' >");
Out.println ("<tr>");
Out.println ("<td>");
Out.println ("username:");
Out.println ("</td>");
Out.println ("<td>");
Out.println ("<input type= ' text ' name= ' username '");
Out.println ("</tr>");
Out.println ("<tr>");
Out.println ("<td>");
Out.println ("city:");
Out.println ("</td>");
Out.println ("<td>");
Out.println ("<select name= ' dept '");
For (Integer I:key) {
Out.println ("<option value= '" +i+ ">" +dept.get (i) + "</option>");
}
Out.println ("</select>");
Out.println ("</td>");
Out.println ("<tr>");
Out.println ("</table>");
Out.println ("</form>");
Out.println ("</body>");
Out.println ("
Out.flush ();
}
}
Example Two: writing a class is used to count the number of times a webpage has been accessed by a client when the Web App Starts. If you restart the Web app, the counter does not start counting the number of visits from 1, but from the last
The results of the statistics are summed up. In practice, it is often necessary to count the number of times a webpage has been accessed by a client since the Web application was published, which requires that when the Web application is terminated, the value of the counter is permanently stored
stored in a file or database, and wait until the Web App restarts, first read the Counter's initial value from the file or database, and then continue counting on that Basis.
The ability to write or read counter values to a file can be done by a custom Myservletcontextlistener class that has the following features:
1. When the Web App starts, read the value of the counter from the file and store the Counter object that represents the counter in the scope of the Web Application. The path to the file where the counter is stored is
Helloapp/count/count.txt.
2. When the Web application terminates, the value of the counter in the scope of the Web application is saved to the Count.txt File. Package servletcontexttest; Import
javax.servlet.ServletContext;
Import javax.servlet.ServletContextEvent;
Import javax.servlet.ServletContextListener; 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{
Reading the value of a counter from a file
BufferedReader reader=new BufferedReader (
New InputStreamReader (context.
getResourceAsStream ("/count/count.txt"));
int Count=integer.parseint (reader.readline ());
Reader.close ();
Create a Counter Object
Counter counter=new Counter (count);
Save the Counter object to the 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 objects from the WEB application scope
Counter counter= (Counter) Context.getattribute ("Counter");
If (counter!=null) {
try{
Write the value of the counter to 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 is registered in the servlet container, and the servlet container invokes the Listener's party when it starts or terminates the Web app.
Method. In the Web. XML file, the <listener> element is used to register the listener with the Container:
<listener>
<listener-class> Servletcontexttest. Myservletcontextlistener<listener-class/></listener>
Note that the package name of the class is to be written in:<listener-class>, such as the following (the package name identifies the path to the Class) <listener>
<listener-class>com.efarm360.action.StartupAction</listener-class>
</listener>
Through the above two examples, it is very clear to understand the use of Servletcontextlistener interface methods and Techniques. When container loads a web application, such as starting
After Container), the contextinitialized () is called, and the contextdestroyed () method is called when the container removes the Web Application. With the results of the TOMCAT console printing
sequencing, you will find that when the Web App starts, the servlet container calls the Contextinitialized () method before invoking the Init () method of lifeinit, and when the Web App terminates, the servlet container first
Use the Lifeinit destroy () method, and then call the contextdestroyed () method. thus, in the life cycle of the Web application, the ServletContext object was first created and destroyed at the Latest.
Technology Sharing: Edith Academy
Ajax resolves Internet Explorer compatibility issues