作用范围
HttpSerletRequest
setAttribute(name,value);
只作用于单次请求,http是无状态,每一次请求都是独立存在的,没有任何交集
HttpSession
setAttribute(name,value);
作用于一整个会话中,在整个会话中都可以使用设置好的属性,如果浏览器关闭当前会话结束,所有设置好的属性全部失效,如果重新打开浏览器,则是一次新的会话
ServletContext
作用于整个服务器,只你的服务器正常开启(不能重启),所有的请求和会话都可使用里面设置属性
作用范围
HttpSerletRequest < HttpSession < ServletContext
这里用最基础的servlet的webservice来做案例代码的解释
@WebServlet("/test")
public class TestServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
//会话 ,针对于整个一次会话有限,针对所有的请求有效,一旦浏览器被×掉,会话结束
HttpSession session=req.getSession();
//只要服务器启动,所有的servlet有效
ServletContext context = this.getServletContext();
//HttpServletRequest
//针对于当前的请求有效,新的请求无效
req.setAttribute("name", "admin");
session.setAttribute("sname", "张三");
context.setAttribute("cname", "李四");
}
}
@WebServlet("/test2")
public class Test2Servlet extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
//请求参数
String name = (String) req.getAttribute("name");
HttpSession session=req.getSession();
String sn = (String) session.getAttribute("sname");
ServletContext con = this.getServletContext();
String cn = (String) con.getAttribute("cname");
System.out.println("请求参数name="+name);
System.out.println("会话session中sanme="+sn);
System.out.println("上下文的context的cname="+cn);
}
}
jsp页面上的简单示例如下
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div>
<a href="test">第一个请求</a>
</div>
<div>
<a href="test2">第二个请求</a>
</div>
</body>
</html>