| 序号 | 对象 | 作用 |
|---|---|---|
| 1 | HttpServletRequest请求对象 | 获取请求信息 |
| 2 | HttpServletResponse响应对象 | 设置响应对象 |
| 3 | ServletConfig对象 | servlet配置对象 |
| 4 | ServletContext对象 | servlet的上下文对象 |
ServletContext对象 ,叫做Servlet的上下文对象,表示一个当前的web应用环境。一个web应用中只有一个ServletContext对象。
创建时机:加载web应用时创建ServletContext对象。
得到对象: 从ServletConfig对象的getServletContext()方法得到
| 序号 | 方法 | 作用 |
|---|---|---|
| 1 | String getContextPath() | 得到当前web应用的路径 |
| 2 | String getInitParameter(String name) Enumeration getInitParameterNames() | 得到web应用的初始化参数 |
| 3 | void setAttribute(String name, Object object) Object getAttribute(String name) void removeAttribute(String name) Enumeration getAttributeNames() | 域对象有关的方法 |
| 4 | RequestDispatcher getRequestDispatcher(String path) | 转发(类似于重定向) |
| 5 | String getRealPath(String path) InputStream getResourceAsStream(String path) | 得到web应用的资源文件 |
String getContextPath() 用在请求重定向的资源名称中
package com.rk.http.e_context;
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 ContextDemo01 extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//1.得到ServletContext对象
//ServletContext context = this.getServletConfig().getServletContext();
ServletContext context = this.getServletContext();//(推荐使用)
//2.得到web应用路径。web应用路径:部署到tomcat服务器上运行的web应用名称
String contextPath = context.getContextPath();
System.out.println(contextPath);
//案例:应用到请求重定向
response.sendRedirect(contextPath + "/index.html");
}
}得到web应用的初始化参数
String getInitParameter(String name)
Enumeration getInitParameterNames()
web应用参数可以让当前web应用的所有servlet获取!!!
在web.xml中使用<context-param>配置web应用的初始化参数
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- 配置web应用参数 --> <context-param> <param-name>AAA</param-name> <param-value>AAA‘s Value</param-value> </context-param> <context-param> <param-name>BBB</param-name> <param-value>BBB‘s Value</param-value> </context-param> <context-param> <param-name>CCC</param-name> <param-value>CCC‘s Value</param-value> </context-param> <servlet> <servlet-name>ContextDemo02</servlet-name> <servlet-class>com.rk.http.e_context.ContextDemo02</servlet-class> </servlet> <servlet-mapping> <servlet-name>ContextDemo02</servlet-name> <url-pattern>/context02</url-pattern> </servlet-mapping> </web-app>
ContextDemo02.java
package com.rk.http.e_context;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 得到web应用参数
* @author RK
*
*/
public class ContextDemo02 extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.write("<h1>web应用的初始化参数</h1>");
ServletContext context = this.getServletContext();//得到ServletContext对象
Enumeration<String> initParameterNames = context.getInitParameterNames();//得到web应用的所有参数名
while(initParameterNames.hasMoreElements())
{
String paramName = initParameterNames.nextElement();
String paramValue = context.getInitParameter(paramName);//得到特定名称的参数值
out.write(paramName + ": " + paramValue + "<br/>");
}
}
}域对象:作用是用于保存数据,获取数据。可以在不同的动态资源之间共享数据。
ServletContext就是一个域对象,作用范围在整个web应用中有效!!!!
保存数据:void setAttribute(String name, Object object)
获取数据: java.lang.Object getAttribute(String name)
删除数据: void removeAttribute(String name)
所有域对象:
HttpServletRequet 域对象
ServletContext域对象
HttpSession 域对象
PageContext域对象
保存数据的ContextDemo03.java
package com.rk.http.e_context;
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;
/**
* 保存数据
* @author RK
*
*/
public class ContextDemo03 extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//1.得到ServletContext域对象
ServletContext context = this.getServletContext();
//2.把数据保存到ServletContext域对象中
context.setAttribute("rk", "lsieun");//保存字符串
Student stu = new Student();
stu.setName("小明");
stu.setAge(20);
context.setAttribute("xiaoming", stu);//保存对象
response.getWriter().write("Save Successfully!!!");
}
}获取数据的ContextDemo04.java
package com.rk.http.e_context;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 获取数据
* @author RK
*
*/
public class ContextDemo04 extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//1.得到ServletContext域对象
ServletContext context = this.getServletContext();
//2.从ServletContext域对象中取出数据
String value = (String)context.getAttribute("rk");
Student stu = (Student)context.getAttribute("xiaoming");
// System.out.println("rk: " + value);
// System.out.println("xiaoming: " + stu);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.write("rk: " + value + "<br/>");
out.write("xiaoming: " + stu + "<br/>");
}
}数据的容器Student.java
package com.rk.http.e_context;
public class Student
{
private String name;
private int age;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
@Override
public String toString()
{
return "[name="+this.name+", age="+this.age+"]";
}
}| 序号 | 角度 | 转发 | 重定向 |
|---|---|---|---|
| 1 | 浏览器地址栏 | a)地址栏不会改变 | a)地址栏会改变,变成重定向到地址。 |
| 2 | 跳转目标 | b)转发只能转发到当前web应用内的资源 | b)重定向可以跳转到当前web应用,或其他web应用,甚至是外部域名网站。 |
| 3 | 是否支持 服务器端 数据传递 | c)可以在转发过程中,可以把数据保存到request域对象中 | c)不能再重定向的过程把数据保存到request中。 |
结论: 如果要使用request域对象进行数据共享,只能用转发技术!!!
ForwardDemo.java
package com.rk.http.f_forward;
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;
/**
* 转发(效果:跳转页面)
* @author RK
*
*/
public class ForwardDemo extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//保存数据到request域对象
request.setAttribute("rk", "lsieun");
/**
* 转发。注意:不能转发当前web应用以外的资源。
*/
//1、第一种写法
/*RequestDispatcher requestDispatcher = this.getServletContext().getRequestDispatcher("/getData");
requestDispatcher.forward(request, response);*/
//2、第二种写法
//this.getServletContext().getRequestDispatcher("/getData").forward(request, response);
//3、第三种写法
request.getRequestDispatcher("/getData").forward(request, response);//等价于上面的代码
}
}GetDataServlet.java
package com.rk.http.f_forward;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 获取转发的数据
* @author RK
*
*/
public class GetDataServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//从request域对象中获取数据
String value = (String)request.getAttribute("rk");
response.getWriter().write(value);
}
}String getRealPath(String path)
InputStream getResourceAsStream(String path)
在src目录下,建立db.properties文件,里面内容如下:
username=lsieun password=123456
在src目录下的db.properties文件,在运行的时候,会被拷贝到下面的文件夹:
%tomcat%/webapps/WebRoot(web发布目录)/WEB-INF/classes/
ResourceDemo.java源代码:
package com.rk.http.g_resource;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 读取web应用下的资源文件(例如properties)
* @author RK
*
*/
public class ResourceDemo extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
ServletContext context = this.getServletContext();
/**
* 1、getRealPath读取,返回资源文件的绝对路径
*/
/*String filePath = context.getRealPath("/WEB-INF/classes/db.properties");
System.out.println("File Path: " + filePath);
InputStream inStream = new FileInputStream(filePath);*/
/**
* 2. getResourceAsStream() 得到资源文件,返回的是输入流
*/
InputStream inStream = context.getResourceAsStream("/WEB-INF/classes/db.properties");
/**
* 上面两种都是通过ServletContext对象的方法来获取Web应用中的资源。
* 下面是通过ClassLoader来获取资源
*/
//InputStream inStream = ResourceDemo.class.getClassLoader().getResourceAsStream("db.properties");
Properties props = new Properties();
props.load(inStream);//读取资源文件
String username = props.getProperty("username");
String password = props.getProperty("password");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.write("username: " + username + "<br/>");
out.write("password: " + password + "<br/>");
System.out.println("username: " + username);
System.out.println("password: " + password);
}
}原文:http://lsieun.blog.51cto.com/9210464/1782266