在某個servlet中,有時我們可能要使用到某個定值,比如說ip,如果直接在servlet中寫ip,當ip發生變化時,就需要從新編譯。解決方法是將ip這個的值配置web.xml中。
配置如下:
(結合上一篇的配置)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<servlet>
<servlet-name>testServlet</servlet-name>
<servlet-class>com.zhongqian.servlet.TestServlet</servlet-class>
<init-param>
<param-name>adminEmail</param-name>
<param-value>[email protected]</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>testServlet</servlet-name>
<url-pattern>/testServlet.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
在裏面添加了參數名adminEmail,取值爲[email protected]。
在對於servlet中取值的方式爲:
String adminEmail = getServletConfig().getInitParameter("adminEmail");
其中getServletConfig()方法繼承至HttpServlet,獲取ServletConfig對象。
另外注意,這個初始化參數只能在對於的servlet中使用。
如果整個應用中都使用這個地址,一種方法是讓servlet讀取初始化參數後,把它保存在一個地方,這樣應用其他部分就能使用,但是這麼一來,就必須知道應用部署時那個servlet最先運行。所以我們應該配置上下文初始化參數。配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<context-param>
<param-name>qq</param-name>
<param-value>253503125</param-value>
</context-param>
<servlet>
<servlet-name>testServlet</servlet-name>
<servlet-class>com.zhongqian.servlet.TestServlet</servlet-class>
<init-param>
<param-name>adminEmail</param-name>
<param-value>[email protected]</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>testServlet</servlet-name>
<url-pattern>/testServlet.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
由上可以看到servlet初始化參數和上下文初始化參數之間配置的區別。
獲取上下文參數的方法:
String qq = getServletContext().getInitParameter("qq");
注:每個servlet一個Servletconifg,每個web應用一個ServletContext
要把初始化參數認爲是部署時常量,可以在運行時得到這些初始化參數,但是不能設置。
獲取ServletContext的方法:
servlet的ServletConfig對象擁有該Servletcontext的一個引用。所以有以下兩種形式:
getServletConfig().getServletContext().getInitParameter();
這樣做不僅合法,而且與下面的代碼是等價的:
this.getServletContext().getInitParameter();
在一個Servlet中,只有一種情況需要通過ServletConfig得到ServletContext,那就是在你的Servlet類沒有擴展HttpServlet或GenericServlet(getServletContext()方法是從GenericServlet中繼承的)。但是使用非HttpServlet的可能性幾乎爲零。所以只需要調用getServletContext()方法就可以了,不過倘若真要看到使用ServletConfig來得到上文中的代碼也是有可能的。如一個輔助類/工具類,這個類傳遞了一個ServletConfig.