日期:2014-05-16  浏览次数:20347 次

jsp+Servlet学习(二)初始化参数

在某个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>253503125@qq.com</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,取值为253503125@qq.com。

在对于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>253503125@qq.com</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.