ServletConfig 类:
ServletConfig 类从类名上来看,就知道是 Servlet 程序的配置信息类。
Servlet 程序和 ServletConfig 对象都是由 Tomcat 负责创建,我们负责使用。 Servlet 程序默认是第一次访问的时候创建,ServletConfig 是每个 Servlet 程序创建时,就创建一个对应的 ServletConfig 对象。
ServletConfig 类的常用作用:
1.可以获取 Servlet 程序的别名 servlet-name 的值
2.获取初始化参数 init-param
3.获取 ServletContext 对象
实例1:
package com.qwy.servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author qwy
* @create 2021-03-09 16:45
**/
public class ServletGetConfinguration extends HttpServlet {
/**
* 初始化方法中获取初始化参数
* @param config
* @throws ServletException
*/
@Override
public void init(ServletConfig config) throws ServletException {
//调用父类的init方法,为了其他方法中使用this.getServletConfig()调用
super.init(config);
//1.获取初始化的参数
String username= config.getInitParameter("username");
System.out.println("username = " + username);
String password= config.getInitParameter("password");
System.out.println("password = " + password);
//2.获取ServeltName
String servletName=config.getServletName();
System.out.println("servletName = " + servletName);
//3.获取ServletContext对象
ServletContext app= config.getServletContext();
System.out.println("app = " + app);
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//注意:在此使用this.getServletConfig(),必须在init()方法中调用 super.init(config);
String name= this.getServletConfig().getInitParameter("username");
System.out.println("name = " + name);
}
}
实例:web.xml
<servlet>
<servlet-name>ServletGetConfinguration</servlet-name>
<servlet-class>com.qwy.servlet.ServletGetConfinguration</servlet-class>
<!--配置初始化参数-->
<init-param>
<!--参数名-->
<param-name>username</param-name>
<!--参数值-->
<param-value>admin</param-value>
</init-param>
<!--配置初始化参数-->
<init-param>
<!--参数名-->
<param-name>password</param-name>
<!--参数值-->
<param-value>123456</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ServletGetConfinguration</servlet-name>
<url-pattern>/config</url-pattern>
</servlet-mapping>
浏览器访问:http://localhost:8080/servlet01/config
控制台输出:
username = admin
password = 123456
servletName = ServletGetConfinguration
app = org.apache.catalina.core.ApplicationContextFacade@2b574b98
name = admin
注意:
1.如果要在其他方法中获取初始化参数,需要在init方法中调用父类的init方法
2.ServletConfig只能获取本Servelt中配置的参数,不能跨Servlet获取