问题:什么是会话?
答:会话简单理解为:用户打开一个浏览器,点击多个超链接,访问服务器多个web资源,然后关闭浏览器,整个过程称之为一个会话
- 会话中遇到的问题
答:每个用户在使用浏览器与服务器进行会话的过程中,不可避免各自会产生一些数据,程序要想办法为每 个用户保存这些数据。
例如:用户点击超链接通过一个servlet购买一个商品,程序应该想办法保存用户购买的 商品,以便用户结帐servlet时,结帐servlet可以得到用户购买的商品为用户结帐。
Cookie
-
Cookie是客户端技术,程序把每个用户的数据以cookie的形式写给用户各自的浏览器,当用户使用浏览器再去访问服务器中的web资源时,就会带着各自的数据去,这样,web资源处理的就是用户各自的数据了。
-
Cookie的API
javax.servlet.http.Cookie类用于创建一个Cookie,reponse接口中定义了一个addCookie()方法,它用于在其响应头中增加一个相应的set-Cookie头字段。同样,request接口中也定义了一个getCookies()方法,它用于获取客户端提交的Cookie,
-
实现输出最后访问浏览器时间
-
Cookie属性
name:名称不能唯一确定一个Cookie,路径可能不同
value:不能存中文
path:默认是写Cookie的那个程序的访问路径;
比如
http://localhost:8080/day_00_servlet/CookieDemo1
path就是:/day__00__servlet/. 看当前创建Cookie的资源(servlet)文件路径
客户端在访问服务器另外资源时,根据访问的路径来决定是否带着Cookie到服务器
当前访问的路径如果是以Cookie的path开头的路径,浏览器就带,否则不带。
maxAge:cookie的缓存时间,默认是-1(默认在浏览器内存中),单位是秒
负数:cookie的数据存在浏览器缓存中
0:删除。路径要保持一致,否则可能删错
正数:缓存(持久化到磁盘上)的时间
- Cookie细节
1、一个Cookie只能标识一种信息,它至少包含有一个标识该信息的名称(NAME)和设置值(VALUE)
2、 一个WEB站点可以给一个WEB浏览器发送多个Cookie,一个浏览器也可以存储多个WEB站点提拱的Cookie
3、浏览器只允许存放300个Cookie,每个站点最多存放20个Cookie,每个Cookie的大小限制为4kb.
4、如果创建一个Cookie,并将它发送给浏览器,默认情况下它是一个会话级别的Cookie(存储在浏览器内存当中),用户退出浏览器之后就会被删除,若希望浏览器将Cookie存储在磁盘上,则需要使用maxAge,并给出一个以秒为单位的时间,将最大时间设为0则是命令浏览器删除该Cookie
注意:删除Cookie时,path必须一致, 否则不会删除。
- 记住用户名
实现历史记录的功能
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 + "]";
}
}
public class DButil {
private static Map<String, Book> map = new HashMap<>();
static {
map.put("1", new Book("1", "红楼梦", 102.1, "李超武"));
map.put("2", new Book("2", "西游记", 10.1, "王锋"));
map.put("3", new Book("3", "三国演义", 101, "李一在"));
map.put("4", new Book("4", "有一种爱", 102.1, "陈清香"));
}
//获取所有book
public static Map<String, Book> findAllBook() {
return map;
}
//通过id 获取对应书籍
public static Book findBookById(String id) {
return map.get(id); //通过键找值
}
}
public class ShowAllBooksServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ShowAllBooksServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.write("本书城有以下书籍:<br/>");
Map<String, Book> Books = DButil.findAllBook();
for(Map.Entry<String, Book> book : Books.entrySet()) {
out.write("<a href='" +request.getContextPath() +"/ShowBookDetail?id=" + book.getKey() +"' target='_blank'>" + book.getValue().getName()+"</a><br/>");
}
out.write("<hr/>您最近浏览的书籍:<br/>");
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
if("historyBookID".equals(cookie.getName())) {
String[] strs = cookie.getValue().split("-");
for (int i = 0; i < strs.length; i++) {
Book book = DButil.findBookById(strs[i]);
out.print(book.getName() + "<br/>");
}
}
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
public class ShowBookDetail extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String Cookie = null;
/**
* @see HttpServlet#HttpServlet()
*/
public ShowBookDetail() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String id = request.getParameter("id");
System.out.println(id);
Book book = DButil.findBookById(id);
//显示图书信息
out.print(book);
String historyBookID = organizeI(id, request);
Cookie ck = new Cookie("historyBookID",historyBookID);
ck.setPath("/");
ck.setMaxAge(Integer.MAX_VALUE);
response.addCookie(ck);
}
private String organizeI(String id, HttpServletRequest request) {
// TODO Auto-generated method stub
Cookie[] cookies = request.getCookies();
if(cookies == null) {
return id;
}
Cookie historyBookID = null;
for(int i = 0; i < cookies.length; i++) {
if("historyBookID".equals(cookies[i].getName())) {
historyBookID = cookies[i];
}
}
if(historyBookID == null) {
return id;
}
String str = historyBookID.getValue();
String[] strs = str.split("-");
LinkedList<String> list = new LinkedList<>(Arrays.asList(strs));
if(list.size() < 3){
if(list.contains(id)) {
list.remove(id);
}
}else{
if(list.contains(id)) {
list.remove(id);
}
else {
list.removeLast();
}
}
list.addFirst(id);
StringBuffer buf = new StringBuffer();
for(int i = 0; i < list.size(); i++) {
if(i > 0) {
buf.append("-");
}
buf.append(list.get(i));
}
System.out.println(buf.toString());
return buf.toString();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
HttpSession
-
Session是服务器端技术,利用这个技术,服务器在运行时可以为每 一个用户的浏览器创建一个其独享的HttpSession对象,由于session为用户浏览器独享,所以用户在访问服务器的web资源时,可以把各自的数据放在各自的Session中,当用户再去访问服务器中的其它web资源时,其它web资源再从用户各自Session中取出数据为用户服务。
-
在WEB开发中,服务器可以为每个用户浏览器创建一个会话对象,(session对象),注意,一个浏览器独占一个session对象(默认情况下),因此,在需要保护用户数据时,服务器程序可以把用户数据写到用户浏览器独占的session中当用户使用浏览器访问其它程序时,其它程序可以从用户的session中取出该用户的数据,为用户服务;
-
Session和Cookie的主要区别?
Cookie是把用户数据写给用户的浏览器。 -
Session技术把用户的数据写给用户独占的Session中。
-
Session对象由服务器创建,开发人员可以调用request对象的getSession()方法得到session对象.
-
Session原理
-
实现简单的购物车
public class ShowAllBooksServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
resp.setContentType("text/html;charset=UTF-8");
PrintWriter out = resp.getWriter();
out.write("本网站有以下好书:<br/>");
Map<String, Book> findAllBook = DButil.findAllBook();
for(Map.Entry<String, Book> map : findAllBook.entrySet()) {
out.write("<a href='"+req.getContextPath()+"/AddCart?id="+map.getKey() +"' target='_blank'> " + map.getValue().getName() + "</a><br/>");
}
out.write("<a href='"+req.getContextPath()+"/ShowCart'>我的购物车</a><br/>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
super.doPost(req, resp);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter writer = response.getWriter();
String id = request.getParameter("id");
Book book = DButil.findBookById(id);
HttpSession session = request.getSession();
ArrayList<Book> list = (ArrayList<Book>)session.getAttribute("cart");
if(list == null ){
list = new ArrayList<Book>();
}
list.add(book);
session.setAttribute("cart", list);
writer.write("购买成功!2秒跳回");
response.setHeader("refresh", "2;url=" +request.getContextPath() + "/ShowAllBooks");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter writer = response.getWriter();
writer.write("购物车有以下商品:<br/>");
ArrayList<Book> list = (ArrayList<Book>)request.getSession().getAttribute("cart");
if(list == null) {
writer.write("空空的购物车哦!!");
response.setHeader("refresh", "2;url=" +request.getContextPath() + "/ShowAllBooks");
return ;
}
for (int i = 0; i < list.size(); i++) {
Book book = list.get(i);
writer.write(book.getName() + "<br/>");
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
- 为什么要学Session?
它也是一个域对象:session、servletContext、request
同一个会话下,可以使一个应用的多个资源共享数据
cookie客户端技术,只能存字符串,session是服务器端的技术,它可以存对象
- 常用的方法
void setAttribute(String name, Object value)
Object getAttribute(String name);
void removeAttribute(String name)
HttpSession.getId();
void setMaxInactiveInterval(int interval);设置存活时间
invalidate()使此会话无效
- getSession()的执行原理