ServletConfig
1. 什么是ServletConfig?
Web容器在启动时,先读取web.xml文件,然后帮每一个servlet建立一个ServletConfig的实例,接着根据web.xml文件的设定建立一些name/value参数,然后Web容器将参数交给ServletConfig,最后产生Servlet的实例时会调用Servlet的init(ServletConfig config)方法把ServletConfig传入Servlet。
在上面也可以看到init方法中的参数就是ServletConfig类型,当TomCat在调用init()方法的时候,就会传递ServletConfig对象,所以我们不能自己去创建ServletConfig对象。
2. 直接看例子
在这里我只设置了一个init-param,大家可以跟上一篇文章里面的context-param作对比
(1)MyServlet类
package com.xiaoming;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException,ServletException
{
PrintWriter out = res.getWriter();
out.print("Hi ");
ServletConfig config = getServletConfig();
String str = config.getInitParameter("name");
out.println(str);
}
}
(2)web.xml。(name,mingxiao)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>com.xiaoming.MyServlet</servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>mingxiao</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/home</url-pattern>
</servlet-mapping>
<context-param>
<param-name>name</param-name>
<param-value>xiaoming</param-value>
</context-param>
<context-param>
<param-name>phone</param-name>
<param-value>HONOR</param-value>
</context-param>
</web-app>
**3.直接运行MyServlet **
运行效果如图所示