Web容器在启动时,会为每个Web应用程序都各自创建一个对应的ServletContext对象。这个Web应用程序中的所有Servlet,都共享同一个ServletContext,因此,Servlet间可以通过ServletContext来进行通讯。
- 设置全局ServletContext的容器参数
在web.xml文件中,通过<context-param>
来设置全局的servletContext参数:
<!--全局servletContext的容器参数-->
<context-param>
<param-name>name</param-name>
<param-value>orton</param-value>
</context-param>
<context-param>
<param-name>mail</param-name>
<param-value>546108715@qq.com</param-value>
</context-param>
- 获取全局ServletContext的容器参数
使用方法:getInitParameter
来获取初始化参数:
@Override
public void init(ServletConfig config) throws ServletException {
ServletContext sc = config.getServletContext();
//获取初始化参数
String name = sc.getInitParameter("name");
String mail = sc.getInitParameter("mail");
System.out.println("name="+name+",mail="+mail);
}
启动tomcat服务器看到输出:
- 通过getAttribute、setAttribute来进行serlvet间数据共享
在servlet1中写入参数address:
@Override
public void init(ServletConfig config) throws ServletException {
ServletContext sc = config.getServletContext();
//获取初始化参数
String name = sc.getInitParameter("name");
String mail = sc.getInitParameter("mail");
System.out.println("name="+name+",mail="+mail);
//设置全局共享的Servlet参数
sc.setAttribute("Address","GD");
}
在servlet2中获取参数address:
@Override
public void init(ServletConfig config) throws ServletException {
ServletContext sc = config.getServletContext();
//设置全局共享的Servlet参数
String address = (String) sc.getAttribute("Address");
System.out.println("on Servlet2,Address=" + address);
}
在web.xml中配置servlet1先装入,servlet2后装入:
<servlet>
<servlet-name>configSerlet</servlet-name>
<servlet-class>com.src.srv.configSvrlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>configSerlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>configSerlet2</servlet-name>
<servlet-class>com.src.srv.configSvrlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>configSerlet2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
启动tomcat,可以看到servlet2获取到了servlet1设置的address属性: