您的位置:首页 > 其它

通过ServletConfig获取Servlet的初始化参数

2016-08-19 22:02 435 查看
web.xml文件中:

<?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>
<!-- 定义Sevlet:给Servlet取个名字 -->
<servlet-name>ServletDemo</servlet-name>
<servlet-class>com.neu.ServletDemo</servlet-class>
<init-param>
<param-name>aaa</param-name>
<param-value>bbb</param-value>
</init-param>
<init-param>
<param-name>encoding</param-name>
<param-value>GBK</param-value>
</init-param>
</servlet>

<servlet-mapping>
<!-- 映射Servlet:给Servlet一个访问地址 -->
<servlet-name>ServletDemo</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

</web-app>

ServletDemo.java文件中:
package com.neu;

import java.io.IOException;
import java.util.Enumeration;

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 ServletDemo extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//使用config了
ServletConfig config = getServletConfig();
test2(config);
}
//得到当前Servlet所有的配置参数
private void test2(ServletConfig config) {
Enumeration e = config.getInitParameterNames();//参数的名字
while(e.hasMoreElements()){
String paramName = (String)e.nextElement();
System.out.println(paramName+"="+config.getInitParameter(paramName));
}
}
//得到指定名称的参数的值
private void test1(ServletConfig config) {
//得到指定名称的参数值
String value = config.getInitParameter("encoding");
System.out.println(value);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}

}
运行结果:

在浏览器中输入:
http://localhost:8080/ServletDemo/hello
服务器的控制台输出:

aaa=bbb
encoding=GBK
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ServletConfig