getInitParameter方法
在ServletConfig和ServletContext都有getInitParameter方法, 这两个方法的都能从web.xml中获取参数,但是是有区别的。
1. 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共享。
2. 调用代码
- 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");
- String s2 = this.getServletContext().getInitParameter("webParam");
- //注意区别,一个是独属于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();
- }
- }
3. 运行结果
bbb aaa