When the Servlet container initializes a Servlet, it will create a ServletConfig object for this Servlet and pass the ServletConfig object as a parameter to the Servlet. The initialization parameter information of the current Servlet can be obtained through the ServletConfig object.
There can be multiple ServletConfig objects in a Web application, and a Servlet can only correspond to one ServletConfig object, that is, the initialization parameters of a Servlet are only valid for the current Servlet.
Get ServletConfig object
There are generally two ways to obtain ServletConfig objects:
1. Extract directly from the init() method with parameters
public class ServletConfigDemo extends HttpServlet { private ServletConfig servletConfig; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Get the name of the Servlet this.servletConfig.getServletName(); } @Override public void init(ServletConfig config) throws ServletException { //Extract the ServletConfig object from the init method with parameters this.servletConfig = config; } }
2. Call the getServletConfig() method provided by GenericServlet to obtain
//Call the getServletConfig method provided by GenericServlet to obtain the ServletConfig object ServletConfig servletConfig = this.getServletConfig();
ServletConfig interface
javax. The servlet package provides a ServletConfig interface, which provides the following methods.
return type | method | Function description |
---|---|---|
String | getInitParameter(String name) | Return the corresponding initialization parameter value according to the initialization parameter name name. |
Enumeration<String> | getInitParameterNames() | Returns an enumerated set of all initialization parameter names of the Servlet. If the Servlet has no initialization parameters, an empty set is returned. |
ServletContext | getServletContext() | Returns a ServletContext object representing the current Web application. |
String | getServletName() | Returns the name of the Servlet, that is, web The value of the <Servlet name> element in XML. |
Configure Servlet initialization parameters
There are two ways to configure Servlet initialization parameters:
- Use web XML configuration initialization parameters;
- Use @WebServlet to configure initialization parameters.
1. Use web XML configuration initialization parameters
On the web One or more <init param> elements can be used in XML to configure initialization parameters for servlets. The code is as follows.
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" metadata-complete="false" version="4.0"> <servlet> <servlet-name>MyServlet</servlet-name> <servlet-class>net.biancheng.www.MyServlet</servlet-class> <!-- Servlet Initialization parameters --> <init-param> <param-name>name</param-name> <param-value>Programming help</param-value> </init-param> <!-- Servlet Initialization parameters --> <init-param> <param-name>URL</param-name> <param-value>www.biancheng.net</param-value> </init-param> </servlet> </web-app>
The above configuration is described as follows:
- The <init param> element is a child element of <Servlet>, which needs to be used in the <Servlet> element, indicating that it is only valid for the current Servlet.
- The <param name> sub element represents the name of the parameter.
- The <param value> sub element represents the value of the parameter.
2. Use @WebServlet to configure initialization parameters
Initialization parameters can also be set for the Servlet through the initParams attribute of the @WebServlet. The code is as follows.
package net.biancheng.www; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(urlPatterns = {"/MyServlet"}, initParams = {@WebInitParam(name = "name", value = "Programming help"), @WebInitParam(name = "URL", value = "www.biancheng.net")}) public class MyServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
Get Servlet initialization parameters
Next, we use an example to demonstrate how to read the initialization parameters of a Servlet through the ServletConfig object.
Take servletDemo project as an example, in net.biancheng Under www package, create a class named ReadConfigServlet with the following code.
package net.biancheng.www; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Programming help www.biancheng.net * Get initialization parameters of Servlet * */ @WebServlet(urlPatterns = { "/ReadConfigServlet" }, initParams = { @WebInitParam(name = "name", value = "Programming help"), @WebInitParam(name = "URL", value = "www.biancheng.net") }) public class ReadConfigServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter writer = response.getWriter(); // Get ServletConfig object ServletConfig config = getServletConfig(); // Get servletName String servletName = config.getServletName(); // Returns a collection of the names of the initialization parameters of the servlet Enumeration<String> initParameterNames = config.getInitParameterNames(); // Traverse the collection to get the initialization parameter name while (initParameterNames.hasMoreElements()) { // Get initialization parameter name String initParamName = initParameterNames.nextElement(); // Get the value of the corresponding initial parameter String initParamValue = config.getInitParameter(initParamName); // Output to page writer.write(initParamName + " : " + initParamValue + "<br/>"); } // Close flow writer.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Start the Tomcat server and enter in the address bar“ http://localhost:8080/servletDemo/ReadConfigServlet ”, access the readconfigservlet, and the results are shown in the following figure.
