public class MyServlet extends HttpServlet { private ServletConfig config; // 定义一个config成员变量,利用servlet的初始化方法,对config赋值 @Override public void init(ServletConfig config) throws ServletException { this.config = config; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // config的常用方法 // 1、根据key获取value String parameter = config.getInitParameter("encoding"); System.out.println(parameter); // 2、获取所有key Enumeration<String> keys = config.getInitParameterNames(); while (keys.hasMoreElements()) { // 获取每一个key String key = keys.nextElement(); String value = config.getInitParameter(key); System.out.println(key + ":" + value); } // 3、获取Servlet的名称 String servletName = config.getServletName(); System.out.println(servletName); // 4、获取ServletContext对象 ServletContext servletContext = config.getServletContext(); System.out.println(servletContext); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
<servlet> <servlet-name>myServlet</servlet-name> <servlet-class>com.hw.web.MyServlet</servlet-class> <!-- 配置servletconfig --> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>myServlet</servlet-name> <url-pattern>/myServlet</url-pattern> </servlet-mapping>
标签:常用,String,方法,System,key,println,config,out From: https://www.cnblogs.com/weiduaini/p/17241343.html