The role of ServletContext

ServletContext

When the web container is started, it will create a corresponding ServletContext object for each web application, which represents the current web application.

Insert picture description here

ServletContext is an object on top of Servlet.

1. Realize shared data:

First store the shared data in the ServletContext through S1,

public class Servlet1 extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        ServletContext context = getServletContext();
        context.setAttribute("message","Hello Servlet");

        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().println("添加到context成功");
    }
}

Then in S2, the shared data can be taken out of the ServletContext

public class Servlet2 extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        ServletContext context = getServletContext();
        String val = (String)context.getAttribute("message");

        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().println(val);
    }
}

Their configuration is:

      <servlet>
        <servlet-name>s1</servlet-name>
        <servlet-class>Servlet1</servlet-class>
      </servlet>
      <servlet>
        <servlet-name>s2</servlet-name>
        <servlet-class>Servlet2</servlet-class>
      </servlet>
  <servlet-mapping>
    <servlet-name>s1</servlet-name>
    <url-pattern>/s1</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>s2</servlet-name>
    <url-pattern>/s2</url-pattern>
  </servlet-mapping>

Finally, visit /s1 and then /s2 to get the deposited message.

2. Get initialization parameters

First, you can web.xmlconfigure some initialization parameters in, and then use the getInitParameter() method of ServletContext to get the value of the initialization parameter

<context-param>
        <param-name>url</param-name>
        <param-value>http://www.baidu.com</param-value>
</context-param>
public class Servlet3 extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        ServletContext context = getServletContext();
        String s = context.getInitParameter("url");
        System.out.println(s);
    }
}

3. Realize request forwarding

Let me talk about the difference between request forwarding and request redirection:

Look at the picture:

Insert picture description here

Forward: A requests B, B finds that A needs resources in C, so B forwards the request to C, C returns to B after processing, and B returns to A again. In this process, A and B each send a request.

Redirect: A requests B, B finds that A's resources are in C, so tell A that you want resources in C, and then A sends a request to C. This process A sent two requests. (So ​​A's request URL address will change)

Realize request forwarding through ServletContext:

public class Servlet3 extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        ServletContext context = getServletContext();
        context.getRequestDispatcher("/s2").forward(req,resp);
    }
}

By getRequestDispatcher()obtaining the forwarding path of the request, it is forwarded through forward()method invocation.

4. Read the resource file

Properties

  • Create new properties in the java directory
  • Create new properties in the resources directory

Found:, 都被打包到了同一个路径下:classeswe commonly call this path classpath.

First, a file stream is needed:

username=root
password=510781

Then read the resource file through ServletContext:

public class Servlet4 extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        ServletContext context = getServletContext();
        InputStream in = context.getResourceAsStream("/WEB-INF/classes/db.properties");
        Properties prop = new Properties();
        prop.load(in);
        String user = prop.getProperty("username");
        String pwd = prop.getProperty("password");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");
        resp.getWriter().println(user+":"+pwd);
    }
}

In the above code, pay attention to the use ServletContextof the getResourceAsStream() method to load resource files.

Pay attention to the path . For the WEB server (Tomcat), the "/" at the beginning of the path represents the basis of the current project:

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-I4dvu9jq-1616852250176)(ServletContext/image-20210327213238051.png)]

The getResourceAsStream() method of ServletContext` can load resource files.

Pay attention to the path . For the WEB server (Tomcat), the "/" at the beginning of the path represents the basis of the current project:

Insert picture description here

That is S1-1.0-.....the path in it. Then the following paths are all calculated according to the project according to the classics. and so,Be sure to make sure that the resource file is included in the corresponding path of the project after deployment and packaging, not the location of the resource file in the source code

Guess you like

Origin blog.csdn.net/qq_40596572/article/details/115272339