ServletConfig对象
在“servlet——14”中我分享了有关使用ServletContext对象的用法,我们可以用它获取web.xml中的全局配置文件,而在 web.xml 中每个 Servlet 也可以进行单独的配置,我们可以使用 ServletConfig 对象
作用
ServletConfig 对象是 Servlet 的专属配置对象,每个 Servlet 都单独拥有一个 ServletConfig 对象,用来获取 web.xml 中的配置信息
使用
- 获取 ServletConfig 对象
- 获取 web.xml 中 servlet 的配置数据
具体代码实现
改变解析编码格式(web.xml)
<init-param>
<param-name>config</param-name>
<param-value>utf-8</param-value>
</init-param>
完整代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>ServletConfigServlet</servlet-name>
<servlet-class>com.youdian.servlet.ServletConfigServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>utf-8</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ServletConfigServlet</servlet-name>
<url-pattern>/sg</url-pattern>
</servlet-mapping>
</web-app>
具体的.java文件中进行测试
package com.youdian.servlet;
import java.io.IOException;
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 ServletConfigServlet extends HttpServlet {
protected void service(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
//获取ServletConfig对象
ServletConfig sc=this.getServletConfig();
//获取web.xml中的配置数据
String code=sc.getInitParameter("config");
System.out.println(code);
}
}