一、ServletConfig对象
1、配置Servlet初始化参数
每一个Servlet可以同时配置多个初始化参数,配置参数时直接使用<init-param>元素即可,其中的<param-name>表示参数名称,<param-value>表示参数的内容,Servlet读取时通过参数名称即可取得参数的内容。例如:
<servlet>
<description></description>
<display-name>InitParamServlet</display-name>
<servlet-name>InitParamServlet</servlet-name>
<servlet-class>com.om.Servlet.InitParamServlet</servlet-class>
<init-param> <!--配置参数 -->
<param-name>ref</param-name> <!--参数名称 -->
<param-value>www.MLDNJAVA.cn</param-value><!--参数内容 -->
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>InitParamServlet</servlet-name>
<url-pattern>/InitParamServlet</url-pattern>
</servlet-mapping
2、通过ServletConfig获取Servlet的初始化参数
当servlet配置了初始化参数后,web容器在创建servlet实例对象时,会自动将这些初始化参数封装到ServletConfig对象中,并在调用servlet的init方法时,将ServletConfig对象传递给servlet。进而,我们通过ServletConfig对象就可以得到当前servlet的初始化参数信息。
ServletConfig对象有以下四个方法:
getServletName(); //获取servlet的名称,也就是我们在web.xml中配置的servlet-name
getServletContext(); //获取ServletContext对象,该对象的作用看下面讲解
getInitParameter(String); //获取在servlet中初始化参数的值。这里注意与全局初始化参数的区分。这个获取的只是在该servlet下的初始化参数
getInitParameterNames(); //获取在Servlet中所有初始化参数的名字,也就是key值,可以通过key值,来找到各个初始化参数的value值。注意返回的是枚举类型.
package com.om.Servlet;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class InitParamServlet
*/
public class InitParamServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("获取servlet的名称"+this.getServletConfig().getServletName());
System.err.println("获取servlet的名称"+this.getServletName());
System.out.println("获取ServletContext对象"+this.getServletConfig().getServletContext());
System.out.println("获取ServletContext对象"+this.getServletContext());
System.out.println("获取参数ref:"
+ this.getServletConfig().getInitParameter("ref"));
System.out.println("获取参数ref:" + this.getInitParameter("ref"));
Enumeration<String> initParameter = this.getServletConfig()
.getInitParameterNames();//获取全部参数
while (initParameter.hasMoreElements()) {
String name = initParameter.nextElement();
System.out.println("参数名:"+name);
System.out.println("参数值:"+this.getServletConfig().getInitParameter(name));
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doGet(request, response);
}
}
运行结果为:
由上面的代码可知,其实可以不用先获得ServletConfig,然后在获取其各种参数,可以直接使用其方法,比如上面我们用的ServletConfig().getServletName();可以直接写成getServletName();而不用在先获取ServletConfig();了,原因就是在GenericServlet中,已经帮我们获取了这些数据,我们只需要直接拿就行。
二、ServletContext对象
WEB容器在启动时,它会为每个WEB应用程序都创建一个对应的ServletContext对象,它代表当前web应用。
ServletConfig对象中维护了ServletContext对象的引用,开发人员在编写servlet时,可以通过ServletConfig.getServletContext方法获得ServletContext对象。由于一个WEB应用中的所有Servlet共享同一个ServletContext对象,因此Servlet对象之间可以通过ServletContext对象来实现通讯。ServletContext对象通常也被称之为context域对象。
1、多个Servlet通过ServletContext对象实现数据共享
setAttribute(String name, Object obj) 在web项目范围内存放内容,以便让在web项目中所有的servlet读能访问到
getAttribute(String name) 通过指定名称获得内容
removeAttribute(String name) 通过指定名称移除内容
先在ServletContextDemo1中将数据data存储到ServletContext对象中。
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletContextDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String param1= "参数1";
/**
* ServletConfig对象中维护了ServletContext对象的引用,开发人员在编写servlet时,
* 可以通过ServletConfig.getServletContext方法获得ServletContext对象。
*/
ServletContext context = this.getServletConfig().getServletContext();//获得ServletContext对象
context.setAttribute("param1", param1); //将data存储到ServletContext对象中
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
在ServletContextDemo2就可以从ServletContext对象中取出数据了,这样就实现了数据共享。
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletContextDemo2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext context = this.getServletContext();
String data = (String) context.getAttribute("param1");//从ServletContext对象中取出数据
response.getWriter().print("param1="+param1);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
2、获取WEB应用的初始化参数
getInitPatameter(String name) //通过指定名称获取初始化值getInitParameterNames() //获得枚举类型
在web.xml文件中使用<context-param>标签配置WEB应用的初始化参数,如下所示:
<!-- 配置WEB应用的初始化参数 -->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/test</param-value>
</context-param>
获取Web应用的初始化参数,代码如下:
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletContextDemo3 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext context = this.getServletContext();
//获取整个web站点的初始化参数
String contextInitParam = context.getInitParameter("url");
response.getWriter().print(contextInitParam);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
3、用servletContext实现请求转发
ServletContext context = this.getServletContext();//获取ServletContext对象
RequestDispatcher rd = context.getRequestDispatcher("/servlet/ServletContextDemo5");//获取请求转发对象(RequestDispatcher)
4、获取web项目资源
(1)、获取web项目下指定资源的路径:getServletContext().getRealPath("/WEB-INF/web.xml");
String path = this.getServletContext().getRealPath("/WEB-INF/classes/db/config/db3.properties");
(2)、获取web项目下指定资源的内容,返回的是字节输入流。InputStream getResourceAsStream(java.lang.String path)。
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/gacl/servlet/study/db4.properties");
(3)、getResourcePaths(java.lang.String path) 指定路径下的所有内容。
Set set=this.getServletContext().getResourcePaths("/WEB-INF");
输出结果为:
三、Servlet跳转
1、客户端跳转
在Servlet中如果要想进行客户端跳转,直接使用HttpServletResponse接口的sendRedirect()方法即可,但是需要注意的是,此跳转只能传递session及application范围的属性,而无法传递request范围的属性。
package com.om.Servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ClientRedirectDemo
*/
public class ClientRedirectDemo extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.getSession().setAttribute("name", "张三") ; //设置session属性
request.setAttribute("info", "设置属性") ; //设置request属性
response.sendRedirect("get_info.jsp") ; //页面跳转
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doGet(request, response);
}
}
接收属性:
<%@ page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<title>XXX</title>
</head>
<%
request.setCharacterEncoding("UTF-8");
%>
<body>
<h2>
session属性:<%=session.getAttribute("name")%></h2>
<h2>
request属性:<%=request.getAttribute("info")%></h2>
</body>
</html>
从程序的运行结果可以发现,由于是客户端跳转,所以跳转后的地址栏是会改变的。但是现在只能接收session属性范围的内容,而request属性范围的内容无法接收到,这是因为request属性范围只有在服务器端跳转中才可以使用。
2、服务器端跳转
在Servlet中没有像JSP中的<jsp:forward>指令,所以,如果要想执行服务器端跳转,就必须依靠RequestDispatcher接口完成,此接口中提供了两种方法。
public void forward(ServletRequest request,ServletResponse response) throws ServletException,IOException public void include(ServletRequest request,ServletResponse response) throws ServletException,IOException
使用RequestDispatcher接口的forward()方法即可完成跳转功能的实现,但是如果要想使用此接口还需要使用ServletRequest接口提供的方法进行实例化。
public RequestDispatcher getRequestDispatcher (String path)
范例:
package com.om.Servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ClientRedirectDemo
*/
public class ClientRedirectDemo extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.getSession().setAttribute("name", "李兴华"); // 设置session属性
request.setAttribute("info", "MLDNJAVA"); // 设置request属性
RequestDispatcher rd = request.getRequestDispatcher("get_info.jsp");
rd.forward(request, response); // 服务器跳转
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doGet(request, response);
}
}
服务器端跳转后,页面的路径不会发生改变,而且此时可以在跳转后的JSP文件中接收到session及request范围的属性。