Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Servletcontext object


May 15, 2021 Servlet



ServletContext is a global space for storing information, where the server begins to exist and the server shuts down before it is released. For your convenience, we'll make a simple comparison between ServletContext and Cookie and Session, as shown below:


Servletcontext object


We can think of ServletContext as a common space that can be accessed by all customers, such as the above image, A, B, C three clients can access.

When the WEB container starts, it creates a corresponding ServletContext for each Web application, which represents the current Web application and is shared by all clients.


Because all servlets in a WEB application share the same ServletContext object, communication between servlet objects can be achieved through the ServletContext object. S ervletContext objects are also commonly referred to as context domain objects. Public chat rooms will use it.

ServletContext objects are destroyed when the web app is closed, Tomcat is closed, or the web application is reloaded


ServletContext usage method


1, how the ServletContext object gets it

this.getServletContext(); 
this.getServletConfig().getServletContext();

2. You can think of it as a table, which is very similar to Session: each row is a property, as follows:

Name (String) Value (Object)


Add properties: setAttribute (String name, Object obj);

Get the value: getAttribute (String name), which returns Object

Delete property: removeAttribute (String name)


3, life cycle

The life cycle of properties in ServletContext starts at creation and ends with server shutdown.


A quick start case:

We created Servlet1 and Servlet2, respectively, to create and read properties in ServletContext:


The doGet method for Servlet1 is:

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=utf-8");
    PrintWriter out = response.getWriter();
    // 获取ServletContext对象的引用
    // 第一种方法

    ServletContext servletContext = this.getServletContext();
    // 第二种方法
    // ServletContext servletContext2 = this.getServletConfig().getServletContext();
    servletContext.setAttribute("name", "小明");
    out.println("将 name=小明  写入了ServletContext");
}

The doGet method for Servlet2 is:

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=utf-8");
    PrintWriter out = response.getWriter();
    // 取出ServletContext的某个属性
    //1.首先获取到ServletContext
    ServletContext servletContext = this.getServletContext();
    //2.取出属性
    String name = (String)servletContext.getAttribute("name");
    out.println("name="+name);
}

With this access to Servlet1 and Servlet2, we can see the output as follows:


Servletcontext object


Servletcontext object


On the face of it, the results of this run don't seem to be any different from Thession, the cookie app, but they're actually completely different. A s long as we don't close Tomcat or realad the app, when we close the current browser, or change to a browser, such as changing from 360 browser to Internet Explorer to access Servlet2 again, we can still see the results! T hat's the biggest difference between cookies and Sessions. This difference is made because ServletContext exists in a common space in server memory that can be accessed by all user clients.


ServletContext app


1. Multiple servlets can be shared between data through the ServletContext object

Similar to Session, we can also implement data sharing through the ServletContext object, but it is important to note that Session can only share data in one client, while the data in ServletContext can be shared across all clients.


2, the implementation of the servlet request forwarding

The request forwarding we learned earlier is through the request object:

request.getRequestDispatcher("/url").forward(request, response);

To illustrate here, ServletContext can also implement request forwarding:

this.getServletContext().getRequestDispatcher("/url").forward(request, response); 

The two forwarding effects are the same.


3, get the initialization parameters of the Web application

We can configure the initialization parameters for the servlet with the label, and then use the servletConfig object to get those parameters, if there is the following MyServlet, which is configured as follows:

<servlet>  
    <servlet-name>MyServlet</servlet-name>  
    <servlet-class>com.gavin.servlet.MyServlet</servlet-class>  
    <init-param>  
        <param-name>encoding</param-name>  
        <param-value>utf-8</param-value>  
    </init-param>  
</servlet>  

You can see that it has an initialization parameter configured: encoding s utf-8, so we need to get this parameter in myServlet source code:

String encoding = this.getServletConfig().getInitParameter("encoding");

Note that the parameter configuration method above is only valid for a specific servlet, and we can use ServletContext to obtain the initialization parameters for the global, entire Web application, which are configured in the web.xml file as this:

<!-- 如果希望所有的Servlet都可以使用该配置,则必须这么做 -->
<context-param>
    <param-name>name</param-name>
    <param-value>gavin</param-value>
</context-param>

We can then use ServletContext to get this parameter in any of the servlets:

String name = this.getServletContext().getInitParameter("name");


4. Read resource files (e.g. properties files) using the ServletContext object

Reading a resource file depends on where the resource file is located, generally in two cases:


4.1: The file is under the WebRoot folder, the root of the Web application. At this point we can use ServletContext to read the resource file.

Suppose we have a dbinfo.properties file under our Web root that configures database information, with name and password properties configured, which can then be read through ServletContext:

// 这种方法的默认读取路径就是Web应用的根目录
InputStream stream = this.getServletContext().getResourceAsStream("dbinfo.properties");
// 创建属性对象
Properties properties = new Properties();
properties.load(stream);
String name = properties.getProperty("name");
String password = properties.getProperty("password");
out.println("name="+name+";password="+password);

4.2: If this file is placed in the src directory, it cannot be read with ServletContext and must be read using a class loader.

// 类加载器的默认读取路径是src根目录
InputStream stream = MyServlet.class.getClassLoader().getResourceAsStream("dbinfo.properties")

If the file is not directly in the src directory at this time, but under a package in the src directory, such as under the com.gavin package, then the class loader adds the path to the package, as follows:

InputStream stream = MyServlet.class.getClassLoader().getResourceAsStream("com/gavin/dbinfo.properties")

To add, ServletContext can only get the full path of the file when it is read at the root of the web application. For example, we have an images folder under the WebRoot folder, and a servlet.jpg picture under the images folder, in order to get the full path of the picture, as follows:

// 如何读取到一个文件的全路径,这里会得到在Tomcat的全路径
String path = this.getServletContext().getRealPath("/images/Servlet.jpg");

In website development, there are many features to use ServletContext, for example

1. Site counter

2. Online user display of the website

3. Simple chat system

In summary, if it involves different users sharing data that is small and does not want to be written to the database, we might consider using the ServletContext implementation.


ServletContext usage recommendations

Because data in ServletContext can be in the server for a long time, which can take up a lot of memory, it is not recommended to add too much data to it when using ServletContext!


Related reading:

Servlet tutorial

Official documentation for the Servlet API