HttpSession
- 在WEB开发中,服务器可以为每个用户浏览器创建一个会话对象(session对象),注意:一个浏览器独占一个session对象(默认情况下)。 因此,在需要保存用户数据时,服务器程序可以把用户数据写到用户浏览器独占的session中,当用户使用浏览器访问其它程序时,其它程序可以从用户的session中取出该用户的数据,为用户服务。
- Session和Cookie的主要区别在于:
• Cookie是把用户的数据写给用户的浏览器。
• Session技术把用户的数据写到用户独占的session中
• cookie客户端技术,只能存字符串。HttpSession服务器端的技术,它可以存对象。
HttpSession的常用方法
把数据保存在HttpSession对象中,该对象也是一个域对象。
void setAttribute(String name,Object value);
Object getAttribute(String name);
void removeAttribute(String name);
HttpSession.getId():
setMaxInactiveInterval(int interval) 设置session的存活时间
invalidate() 使此会话无效
例子演示(购物车的简单实现):
Session1.java(购买页面)
public class Session1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//根据id得到书
String id = request.getParameter("id");
Book book = DBUtil.findBookById(id);
//得到session对象
HttpSession session = request.getSession();
//从session中取出list(购物车)
List<Book> list = (List<Book>)session.getAttribute("cart");
if(list==null){
list = new ArrayList<Book>();
}
list.add(book);//list不会存放重复的数据
session.setAttribute("cart", list);//把list放回到session域中
out.print("购买成功!");
String url = request.getContextPath()+"/servlet/session2";
response.setHeader("refresh", "2;url="+response.encodeURL(url));
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
Session2.java(首页)
public class Session2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置编码
response.setContentType("text/html;charset=UTF-8");
//添加输出流
PrintWriter out = response.getWriter();
//获取Session
request.getSession();
out.print("本网站有以下好书:<br/>");
Map<String, Book> books = DBUtil.findAllBooks();
for (Map.Entry<String, Book> book : books.entrySet()) {
String url = request.getContextPath()+"/servlet/session1?id="+book.getKey();
out.print("<a href='"+response.encodeURL(url)+"' >"+book.getValue().getName()+"</a><br/>");
}
String url2 = request.getContextPath()+"/servlet/session3";
out.print("<a href='"+response.encodeURL(url2)+"'>查看购物车</a>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
Session3.java(购物车页面)
public class Session3 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("购物车有以下商品:<br/>");
HttpSession session = request.getSession();
//得到session对象
List<Book> books = (List<Book>)session.getAttribute("cart");
if(books==null){
out.print("你还什么都没买呢");
//2秒后返回
response.setHeader("refresh", "2;url="+request.getContextPath()+"/servlet/showAllBooksServlet");
//response.sendRedirect(request.getContextPath()+"/servlet/showAllBooksServlet");
return;
}
for (Book book : books) {
out.write(book.getName()+"<br/>");
}
//设置存活时间
session.setMaxInactiveInterval(60*5);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
实体类:
Book.java
public class Book {
private String id;
private String name;
private double price;
private String author;
public Book(String id, String name, double price, String author) {
super();
this.id = id;
this.name = name;
this.price = price;
this.author = author;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", price=" + price
+ ", author=" + author + "]";
}
}
DBUtil.java
public class DBUtil {
private static Map<String, Book> books = new HashMap<String, Book>();
static{
books.put("1", new Book("1", "金瓶梅", 20, "王瑞鑫"));
books.put("2", new Book("2", "葵花宝典", 20, "杨成毅"));
books.put("3", new Book("3", "九阴真经", 30, "陈光"));
books.put("4", new Book("4", "玉女心经", 10, "陈志家"));
}
//得到所有书
public static Map<String, Book> findAllBooks(){
return books;
}
/**
* 根据id查找指定的书
* @param id
* @return
*/
public static Book findBookById(String id){
return books.get(id);
}
}
getSession()的原理
HttpSession request.getSession():内部执行原理
- 1 获取名称为JSESSIONID的cookie的值。
- 2 没有这样的cookie,创建一个新的HttpSession对象,分配一个唯一的SessionID,并且向客户端写了一个名字为JSESSIONID=sessionID的cookie
- 3 有这样的Cookie,获取cookie的值(即HttpSession对象的值),从服务器的内存中根据ID找那个HttpSession对象:
- 找到了:取出继续为你服务。
- 找不到:从2开始。
- 4 HttpSession request.getSession(boolean create):
参数:
true:和getSession()功能一样。
false:根据客户端JSESSIONID的cookie的值,找对应的HttpSession对象,找不到返回null(不会创建新的,只是查询)。