Study notes 3: ServletContext object

ServletContext object

Every web application has and only one ServletContext object, also known as the Application object, which is related to the application (related to the project).

When the web container is started, a corresponding ServletContext object will be created for each WEB application

This object has two major functions,

First, as a domain object to share data, at this time the data is shared in the entire application;

Second, the current application related information is stored in this object. For example, the current server information can be obtained through the getServerInfo() method, and the real path of the resource can be obtained by getRealPath(String path).

Obtaining the ServletContext object

There are many ways to obtain the ServletContext object, such as:

  1. Obtained through the Request object
ServletContext servletContext = req.getServletContext();
  1. Obtained by session object
ServletContext servletContext1 = req.getSession().getServletContext();
  1. Get directly (can only be called in servlet)
ServletContext servletContext = getServletContext();
  1. Obtained by the ServletConfig object
ServletContext servletContext3 = getServletConfig().getServletContext();

Common method

  1. Get current server version information
String serverInfo = req.getServletContext().getServerInfo();
  1. Get the real path of the current project
String realPath = req.getServletContext().getRealPath("/");
System.out.println("真实路径:"+realPath);

ServletContext domain object

ServletContext can also be used as a domain object. By accessing data to ServletContext, the entire application can share certain data.

It is not recommended to store too much data, because the data in the ServletContext will always be saved once it is stored and not manually removed.

//获取ServletContext对象
ServletContext servletContext = request.getServletContext();
//设置域对象
servletContext.setAttribute("name","zhangsan");
//获取域对象
String name = (String) servletContext.getAttribute("name");
//移除域对象
servletContext.removeAttribute("name");

Servlet three domain objects

  1. The request domain object
    is valid in a request, request forwarding is valid, and redirection is invalid

  2. The session domain object
    is valid in a session, both request forwarding and redirection are valid, and invalid after the session is destroyed

  3. The servletContext domain object
    is valid in the entire application and becomes invalid after the server is shut down.

Guess you like

Origin blog.csdn.net/qq_40492885/article/details/115264260