一、作用
ServletConfig对象是Servlet的专属配置对象,每个Servlet都单独拥有一个ServletConfig对象,用来获取web.xml中的配置信息。
二、使用:
获取ServletConfig对象:
- 获取ServletConfig对象:ServletConfig sg = this.getServletConfig();
- 获取web.xml中的属性配置:sg.getInitParameter(name)
1 public class TestServletConfig extends HttpServlet { 2 @Override 3 protected void service(HttpServletRequest req, HttpServletResponse resp) 4 throws ServletException, IOException { 5 //获取ServletConfig对象 6 ServletConfig sg = this.getServletConfig(); 7 //设置请求编码格式 8 req.setCharacterEncoding(sg.getInitParameter("code")); 9 //设置响应编码格式 10 resp.setContentType("text/html;charset=utf-8"); 11 //获取请求信息 12 //获取web.xml中的属性配置 13 String flag = sg.getInitParameter("flag"); 14 System.out.println(flag); 15 //获取用户请求信息 16 String uname=req.getParameter("uname"); 17 //处理请求信息 18 System.out.println(uname); 19 //响应处理结果 20 } 21 }
web.xml中servlet的配置信息
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> 3 <display-name>11-ServletConfig</display-name> 4 <servlet> 5 <description>This is the description of my J2EE component</description> 6 <display-name>This is the display name of my J2EE component</display-name> 7 <servlet-name>TestServletConfig</servlet-name> 8 <servlet-class>com.bjsxt.servlet.TestServletConfig</servlet-class> 9 <!-- 配置当前Servlet的属性信息 --> 10 <init-param> 11 <param-name>flag</param-name> 12 <param-value>true</param-value> 13 </init-param> 14 <init-param> 15 <param-name>code</param-name> 16 <param-value>utf-8</param-value> 17 </init-param> 18 </servlet> 19 20 <servlet-mapping> 21 <servlet-name>TestServletConfig</servlet-name> 22 <url-pattern>/tg</url-pattern> 23 </servlet-mapping> 24 25 </web-app>