web.xml里面可以定义两种参数:<context-param> 和</init-param>
(1)application范围内的参数,存放在servletcontext中,在web.xml中配置如下:
1 <context-param> 2 <param-name>context/param</param-name> 3 <param-value>avalible during application</param-value> 4 </context-param>
(2)servlet范围内的参数,只能在servlet的方法doGet()、doPost()和init()中取得,在web.xml中配置如下:
1 <servlet> 2 <servlet-name>MainServlet</servlet-name> 3 <servlet-class>com.wes.controller.MainServlet</servlet-class> 4 <init-param> 5 <param-name>init/param</param-name> 6 <param-value>avalible in servlet init()</param-value> 7 </init-param> 8 <load-on-startup>0</load-on-startup> 9 </servlet>
在servlet中可以通过代码分别取用:
java 代码
1 public void doGet(HttpServletRequest request, HttpServletResponse response)
2 throws ServletException, IOException {
3
4 response.setContentType("text/html");
5 PrintWriter out = response.getWriter();
6 out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">");
7 out.println("<HTML>");
8 out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
9 out.println(" <BODY>");
10 out.print(" This is ");
11 out.print(this.getClass());
12 out.println(this.getServletConfig().getInitParameter("init/param"));
13 out.println(this.getServletConfig().getServletContext().getInitParameter("context/param"));
14 out.println(", using the GET method");
15 out.println(" </BODY>");
16 out.println("</HTML>");
17 out.flush();
18 out.close();
19 }
通过URL访问该Servlet:

第一种参数只能在servlet的方法中通过this.getServletConfig().getInitParameter("init/param")取得
第二种参数在servlet里面可以通过this.getServletConfig().getServletContext().getInitParameter("context/param")得到
解析:init-param只属于一个servlet所有,所以只有在该Servlet的方法中才能调用。
而context-param属于整个应用程序所有 ,不仅是在servlet中可以得到,jsp文件中也可以得到.
在jsp中config就相当于这里的servletContext,例如在index.jsp中<%=config.getServletContext().getInitParameter("context/param")%>

运行结果:

在action中ServletActionContext.getServletContext().getInitParameter("context/param").
