getInitParameter()方法来抓取web.xml中的参数

在代码中读取web.xml中的一些参数
例:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5" 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_2_5.xsd">

<context-param>
<param-name>webParam</param-name>
<param-value>aaa</param-value>
</context-param>

<servlet>
<servlet-name>test</servlet-name>
<servlet-class>Test</servlet-class>
<init-param>
<param-name>servletParam</param-name>
<param-value>bbb</param-value>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>

</web-app>
注:区分配置文件中,对参数的配置的不同. servletParam这个参数是属于Test这个Servlet的; 而webParam这个参数是属于web应用的,被各个servlet共享

//在servlet中用printwriter写出html的效果
public class Test extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String s1 = this.getInitParameter("servletParam"); //调取的是init-param 结果是bbb
String s2 = this.getServletContext().getInitParameter("webParam"); //调取的是context-param 结果是aaa
//注意区别,一个是独属于Test这个Servlet的参数,一个是web范围的参数,
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.println(s1);
out.println(s2);
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}

}

2018-08-27

posted @ 2018-08-27 16:27  撞撞鱼奋斗  阅读(602)  评论(0编辑  收藏  举报