Javaweb - ServletConfig and ServletContext interfaces

Keywords: xml Java encoding Tomcat

Links to the original text: http://c.biancheng.net/view/3998.html

Article directory

ServletConfig interface

When running a Servlet program, you may need some auxiliary information, such as the encoding used by the file, the shared information using the Servlet program, etc. This information can be configured in a web.xml file using one or more elements. When Tomcat initializes a servlet, the configuration information of the servlet is encapsulated in the ServletConfig object, which can be passed to the servlet by calling init (ServletConfig config).

The ServletConfig interface defines a series of methods for obtaining configuration information, as shown in Table 1.
Table 1 Common methods of ServletConfig interface

Next, take the getInitParameter() method as an example to illustrate the use of this method step by step.
1) Create Servlet
Create a Servlet class named TestServlet02 in the com.mengma.servlet package, and write code in the class to read parameter information in the web.xml file, as shown below.

package com.mengma.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestServlet02 extends HttpServlet {

    protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        ServletConfig config = this.getServletConfig(); //Get the ServletConfig object
        String param = config.getInitParameter("encoding");
        out.println("encoding=" + param);
    }

    protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

}

2) Configuration parameter information
Configure some parameter information for Servlet in web.xml file. The specific configuration code is as follows:

<servlet>
  <servlet-name>TestServlet02</servlet-name>
  <servlet-class>com.mengma.servlet.TestServlet02</servlet-class>
  <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
  </init-param>
</servlet>
<servlet-mapping>
  <servlet-name>TestServlet02</servlet-name>
  <url-pattern>/TestServlet02</url-pattern>
</servlet-mapping>

In the parameter information above, the node represents the parameter to be set, the name of the parameter in the node represents the value of the parameter, the node configures a parameter named encoding for TestServlet02, and sets the value of its parameter to UTF-8.
3) Run the project and view the results
Start the Tomcat server and enter the address http://localhost:8080/servletDemo01/TestServlet02 in the browser's address bar to access TestServlet02, as shown in Figure 1.

As you can see from Figure 1, the encoding information configured for TestServlet02 in the web.xml file is read out. Thus, the parameter information in the web.xml file can be obtained through the ServletConfig object.

ServletContext interface

When Tomcat starts up, Tomcat creates a unique ServletContext object for each Web application to represent the current Web application, which encapsulates all the information of the current Web application. This object can be used to obtain initialization information of Web applications, read resource files, etc. The different functions of the ServletContext interface are explained below.

1. Get initialization parameters for Web applications
In the web.xml file, not only the mapping information of the Servlet can be configured, but also the initialization information of the whole Web application can be configured. The configuration of initialization parameters for Web applications is as follows:

<context-param>
    <param-name>XXX</param-name>
    <param-value>xxx</param-value>
</context-param>
<context-param>
    <param-name>AAA</param-name>
    <param-value>aaa</param-value>
</context-param>

In the example above, the element is located in the root element, its sub-elements and the names and parameters used to specify the parameters, respectively. To obtain information about these parameter names and values, getInitParameterNames() and getInitParameter (String name) methods defined in the ServletContext interface can be used to obtain these parameters respectively.
The following example demonstrates how to use the ServletContext interface to obtain initialization parameters for Web applications.

1) Configure initialization parameter information and Servlet information in the web.xml file of servletDemo01 project. The code is as follows:

<context-param>
    <param-name>username</param-name>
    <param-value>admin</param-value>
</context-param>
<context-param>
    <param-name>password</param-name>
    <param-value>1234</param-value>
</context-param>
<servlet>
    <servlet-name>TestServlet03</servlet-name>
    <servlet-class>com.mengma.servlet.TestServlet03</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>TestServlet03</servlet-name>
    <url-pattern>/TestServlet03</url-pattern>
</servlet-mapping>

2) Create a class named TestServlet03 in the com.mengma.servlet package of the project, which uses the ServletContext interface to obtain configuration information in web.xml, as shown below.

package com.mengma.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

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 TestServlet03 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        // Get the ServletContext object
        ServletContext context = this.getServletContext();
        // Get the Enumeration object with all initialization parameter names
        Enumeration<String> paramNames = context.getInitParameterNames();
        // Traverse through all initialization parameter names, get the corresponding parameter values and print them.
        while (paramNames.hasMoreElements()) {
          String name = paramNames.nextElement();
          String value = context.getInitParameter(name);
          out.println(name + ":" + value);
          out.println("<br/>");
    }
}

    public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
        this.doGet(request, response);
    }
}

In the above code, when the ServletContext object is obtained through this.getServletContext() method, the getInitParameterNames() method is first called to get the Enumeration object containing all initialization parameter names, and then the Enumeration object is traversed through getInitParamter (Stri) according to the parameter name obtained. The corresponding parameter values are obtained by ng name method.

3) Start the Tomcat server and enter the address http://localhost:8080/servletDemo01/TestServlet03 in the browser's address bar to access TestServlet03. The browser's display results are shown in Figure 2.

As you can see from Figure 2, the configuration information in the web.xml file is read out. Thus, the initialization parameters of the Web application can be obtained through the ServletContext object.

2. Reading Resource Files in Web Applications
In practical development, it is sometimes necessary to read some resource files in Web applications, such as configuration files and log files. To this end, some methods of reading Web resources are defined in the ServletContext interface, which are implemented by the Servlet container. The Servlet container returns the I/O stream of the associated resource file or the absolute path of the resource file in the system according to the path of the resource file relative to the Web application.

Table 2 lists the methods used to obtain resource paths in the ServletContext interface.

After understanding the methods used in the ServletContext interface to obtain the Web resource path, the following step-by-step demonstration of how to use the ServletContext object to read the resource file is presented by a case study.
The case demonstrates step by step how to use the ServletContext object to read resource files.

1) Create a file named itcast.properties in the src directory of the servletDemo01 project, and enter the configuration information as shown below in the created file:

username=admin
password=1234

2) Create a Servlet class named TestServlet04 in the com.mengma.servlet package. Use this class to read the content of itcast.properties resource file. Actually, the modern code is as follows.

package com.mengma.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Properties;

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 TestServlet04 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        ServletContext context = this.getServletContext();
        PrintWriter out = response.getWriter();
        // Get the input stream object in the relative path
        InputStream in = context
            .getResourceAsStream("/WEB-INF/classes/itcast.properties");
        Properties pros = new Properties();
        pros.load(in);
        out.println("username=" + pros.getProperty("username") + "<br/>");
        out.println("password=" + pros.getProperty("password") + "<br/>");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

        this.doGet(request, response);
    }
}

In the above code, the getResourceAsStream (String path) method of ServletContext is used to obtain the input stream object associated with the itcast.properties resource file, where the path parameter must start with a forward slash (/) to indicate the relative path of the itcast.properties file to the Web application.

3) Start the Tomcat server and enter the address http://localhost:8080/servletDemo01/TestServlet04 in the browser's address bar to access TestServlet04. The browser's display results are shown in Figure 3.

As you can see from Figure 3, the contents of the itcast.properties resource file have been read out. Thus, using ServletContext, you can read resource files in Web applications.

Posted by MJH Mike on Mon, 16 Sep 2019 04:56:38 -0700