web.xml裡面可以定義兩種參數: 和
(1)application範圍内的參數,存放在servletcontext中,在web.xml中配置如下:
1
2 context/param
3 avalible during application
4
(2)servlet範圍内的參數,隻能在servlet的方法doGet()、doPost()和init()中取得,在web.xml中配置如下:
1
2 MainServlet
3 com.wes.controller.MainServlet
4
5 init/param
6 avalible in servlet init()
7
8 0
9
在servlet中可以通過代碼分别取用:
java 代碼
1 public voiddoGet(HttpServletRequest request, HttpServletResponse response)2 throwsServletException, IOException {3
4 response.setContentType("text/html");5 PrintWriter out =response.getWriter();6 out.println(""-//W3C//DTD HTML 4.01 Transitional//EN\">");7 out.println("");8 out.println("
A Servlet");9 out.println(" ");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(" ");16 out.println("");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中
運作結果:
在action中ServletActionContext.getServletContext().getInitParameter("context/param").