一、ServletConfig 对象
ServletConfig 对象是它所对应的 Servlet 对象的相关配置信息
特点:1、每个Servlet对象都有一个 ServletConfig 对象和它相对应,2、ServletConfig 对象在多个 Servlet 对象之间是不能共享的
1、 使用 web.xml 配置初始化参数
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>GetConifgServlet</servlet-name>
<servlet-class>net.zixue.servlet.GetConifgServlet</servlet-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>GetConifgServlet</servlet-name>
<url-pattern>/getconfig</url-pattern>
</servlet-mapping>
</web-app>
2、获取参数
package net.zixue.servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class GetConifgServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletConfig servletConfig = this.getServletConfig();
String encoding = servletConfig.getInitParameter("encoding");
System.out.println("encoding=" + encoding);
}
}
2、ServletContext 对象
ServletContext 即Servlet 上下文对象,该对象表示当前的 web 应用环境信息
域对象:在不同资源之前共享数据,保存数据,获取数据,ServletContext 对象通常称为 Context 域对象,
<!-- 在web.xml中配置初始化参数 -->
<context-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</context-param>
// Servlet
@WebServlet(name = "Test3Servlet", urlPatterns = "/test3")
public class Test3Servlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String encoding = this.getServletContext().getInitParameter("encoding");
System.out.println(encoding);
}
}