Home >Java >javaTutorial >What is ServletConfig
ServletConfig refers to the configuration information of the current servlet in the web.xml file. Developers can obtain the initialization parameter information of the current servlet through the ServletConfig object.
String getServletName() -- 获取当前Servlet在web.xml中配置的名字 String getInitParameter(String name) -- 获取当前Servlet指定名称的初始化参数的值 Enumeration getInitParameterNames() -- 获取当前Servlet所有初始化参数的名字组成的枚举 ServletContext getServletContext() -- 获取代表当前web应用的ServletContext对象###In the Servlet configuration file, you can use one or more
<servlet> <servlet-name>ServletConfigTest</servlet-name> <servlet-class>com.vae.servlet.ServletConfigTest</servlet-class> <init-param> <param-name>name1</param-name> <param-value>value1</param-value> </init-param> <init-param> <param-name>encode</param-name> <param-value>utf-8</param-value> </init-param> </servlet>###Then get the above two parameters in the code. The code implementation is as follows: ###
package com.vae.servlet; import java.io.IOException; import java.util.Enumeration; 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 ServletConfigTest extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletConfig config = this.getServletConfig(); //拿到init方法中的ServletConfig对象 // --获取当前Servlet 在web.xml中配置的名称(用的不多) String sName = config.getServletName(); System.out.println("当前Servlet 在web.xml中配置的名称:"+sName); // --获取当前Servlet中配置的初始化参数(只能获取一个)经常用到 // String value = config.getInitParameter("name2"); // System.out.println(value); // --获取当前Servlet中配置的初始化参数(全部获取)经常用到 Enumeration enumration = config.getInitParameterNames(); while(enumration.hasMoreElements()){ String name = (String) enumration.nextElement(); String value = config.getInitParameter(name); System.out.println(name+":"+value); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }###The core code is line 17. Get the ServletConfig object in the init method through this.getServletConfig() method, and then obtain the configuration information. ######Run the program and the background print log is as follows: ############
The above is the detailed content of What is ServletConfig. For more information, please follow other related articles on the PHP Chinese website!