ServletConfig接口
Servlet容器初始化Servlet对象时会为Servlet创建一个ServletConfig对象,在ServletConfig对象中包含了Servlet的初始化参数信息,此外ServletConfig对象还与当前web应用中的ServletContext对象关联,Servlet容器在调用Servlet对象的init(SevletConfig config)方法时会把ServletConfig对象作为一个参数传递给Servlet对象,这个方法是的Servlet和ServletConfig对象之间建立关联,
每个初始化参数包含一对参数名和参数值,在web.xml中初始化参数时可以用<init-param>来设置参数值,<param-name>表示参数名,<param-value>表示参数值。
以下代码为一个FontServlet类设置了两个初始化参数size和color.
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"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>Font</servlet-name> <servlet-class>com.demo.servlet.FontServlet</servlet-class> <init-param> <param-name>color</param-name> <param-value>red</param-value> </init-param> <init-param> <param-name>size</param-name> <param-value>35</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Font</servlet-name> <url-pattern>/font</url-pattern> </servlet-mapping>
</web-app>
|
FontServle.java
package com.demo.servlet;
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter;
/** * Created by 谭雪娇 on 2017/4/6. */ public class FontServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException ,IOException{ String word=request.getParameter("word"); if(word==null){ word="Hello"; } //读取初始化参数 String color=getInitParameter("color"); String size=getInitParameter("size"); System.out.println("ServletName:"+getServletName());//打印ServletName:Font /**设置HTTP响应正文得MIME类型及字符编码*/ response.setContentType("text/html;charset=UTF-8"); /*输出html文档*/ PrintWriter out=response.getWriter(); out.println("<html><head><title>FontServlet</title></head>"); out.println("<font size=‘"+size+"‘color=‘"+color+"‘>"+word+"</font>"); out.println("</body></html>"); out.close();
} }
|
tomcat服务器控制台结果
浏览器结果