Load. properties file contents to memory----Tomcat service start and stop listening (using Servletcontextlistener)

Source: Internet
Author: User
Tags numeric value terminates

Use Servletcontextlistener to create and close the cache when the server starts and shuts down. 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 various programs within the Web application. Because the context can be used to save resources and share, the biggest application I know of ServletContext is that the Web cache----read infrequently changed content into memory, so the server does not need to slow disk I/O when responding to requests.

Servletcontextlistener is a ServletContext listener, if servletcontext changes, such as when the server is started ServletContext is created and the server shuts down ServletContext will be destroyed.

in the JSP file, application is an instance of ServletContext , created by default by the JSP container. The Getservletcontext () method is invoked in the Servlet to get an instance of ServletContext.

The way we use caching is probably:

1: The Servletcontextlistener contextinitialized () method is invoked when the server is started, so it creates a good cache inside. A cached content generation class can be read from a file or from a database, and the cache class is saved in an instance of ServletContext with the Servletcontext.setattribute () method.

2: The program uses Servletcontext.getattribute () to read the cache. If it is a JSP, use Application.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 wait for changes to accumulate to a certain program to save, or you can save in the next step .

3: The Servletcontextlistener contextdestroyed () method is invoked when the server is about to close, so the cached changes are saved inside. Save the changed cache back to the file or database to update the original content. Import User;
my own classimport Databasemanager;
my own classimport 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;
}
}


Servletcontextlistener of the Department of Distribution

You implement (implements) Servletcontextlistener after compiling, put it in the correct web-inf/classes directory, change the Web.xml file in the Web-inf directory, add in the Web-app node


< listener >
< Listener-class > Myservletcontextlistener </listener-class >
</Listener >

Finally, grasp the usefulness of this:

1. When Tomcat starts, it loads the contents of the dictionary table data or the. properties file into memory. You can define a static constant class to store.

Public class Cunfangconstants {
    public static String ServerIP = null;
   &NBSP;PU Blic static String username= null;
    


public class mycontextlistener implements  servletcontextlistener {
    private ServletContext context =  NULL;&NBSP

    public void contextinitialized (servletcontextevent  event)  {  
        cunfangconstants.serverip= " 1.1.1.1 "//Here written dead, the specific IP address can be taken from the database, or from the. properties file, take the
    } 

     public void contextdestroyed (servletcontextevent event)  { 
  &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;CUNFANGCONSTANTS.SERVERIP=&NBSP;NULL;&NBSP
    }
}

This enables you to load the contents of a database or a. properties file into the Cunfangconstants class, and then simply call it (Cunfangconstants.serverip) in Java.

In the JSP, in addition to the above mentioned Application.getattribute () can be called, you can also call this:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "
pageencoding= "UTF-8" iserrorpage= "true"%>
<%@ page import= "com.supc.wczw.cunfangConstants" language= "java"%>
<%@ page import= "java.lang.String" language= "java"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01//en" "HTTP://WWW.W3.ORG/TR/HTML4/STRICT.DTD" >
<title></title>
<script type= "Text/javascript" >
Alert (' <%=cunfangConstants.ServerIP%> ');
</script>
<body>
</body>


===================================================

"Attach: Specific use cases of application in JSP"

Application in a JSP has two meanings, first, "server-wide" in the range of four properties. Second, represents a built-in object (JSP has nine large built-in objects).
In other words, it is an object that is created when the server is turned on and disappears when the server shuts down. Example: monitor implementation, servletcontextattribute.jsp: <%@ page language= "java" import= "java.util.*" pageencoding= "iso-8859-1"% >  

===================================================================================


If you don't know anything about Servletcontextlistener, go through the Servletcontextlistener article in detail:

There is a Servletcontextlistener interface in the Servlet API that listens to the lifecycle of the ServletContext object, actually listening to the lifecycle 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 is initialized to the filter, and the servlet 跏 Thistle ?/p> 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 of routine 4-9 in section 4.4.1 of this chapter 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 ();

Creating 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 objects from Web application scope

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);

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.