Session

一、Session的简介:

  在WEB开发中,服务器可以为每个用户浏览器创建一个会话对象(session对象),注意:一个浏览器独占一个session对象(默认情况下)。因 此,在需要保存用户数据时,服务器程序可以把用户数据写到用户浏览器独占的session中,当用户使用浏览器访问其它程序时,其它程序可以从用户的 session中取出该用户的数据,为用户服务。

二、Session和Cookie对象的区别:

  • Cookie是把用户的数据写给用户的浏览器。
  • Session技术把用户的数据写到用户独占的session中。
  • Session对象由服务器创建,开发人员可以调用request对象的getSession方法得到session对象。

三、Session的生命周期:

A、什么时候产生Session

  只有访问JSP、Servlet等程序时才会创建Session,只访问HTML、IMAGE等静态资源并不会创建Session,可调用request.getSession(true)强制生成Session。

B、什么时候销毁:

  1. 服务器会把长时间没有活动的Session从服务器内存中清除,此时Session便失效。Tomcat中Session的默认失效时间为30分钟。

  2. 调用Session的invalidate方法。

四、Session的getSession()的方法

  Request.getSession();//可以创建session

  Request.getSession(false);//只会调用session

五、Session的实现原理:

  服务器创建session出来后,会把session的id号,以cookie的形式回写给客户机,这样,只要客户机的浏览器不关,再去访问服务器时,都 会带着session的id号去,服务器发现客户机浏览器带session id过来了,就会使用内存中与之对应的session为之服务。但是,cookie的有效时间是没有设置的,通过覆盖方法,可以通过以下方法解决.

//获取session的Id
String sessionId = session.getId();
//将session的Id存储到名字为JSESSIONID的cookie中
Cookie cookie = new Cookie("JSESSIONID", sessionId);
//设置cookie的有效路径
cookie.setMaxAge(1800);
cookie.setPath(request.getContextPath());
response.addCookie(cookie);

 用户禁止cookie:可以通过URL,来解决:

 //response. encodeURL(java.lang.String url)用于对表单action和超链接的url地址进行重写
url = response.encodeURL(url);//将超链接的url地址进行重写
out.println(book.getName()  + "   <a href='"+url+"'>购买</a><br/>");

 六、URL重新

  response.encodeRedirectURL(java.lang.String url) 用于对sendRedirect方法后的url地址进行重写。

  response.encodeURL(java.lang.String url)用于对表单action和超链接的url地址进行重写

七、范例:禁用Cookie后servlet共享Session中的数据

ListBookServlet

 

package cn.lyjs.session;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class ListBookServlet extends HttpServlet {

    
    public 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> map=DB.getMap();
         request.getSession();
         for(Map.Entry<String, Book> entry:map.entrySet()){
             Book book=entry.getValue();
             String url= response.encodeURL("/day08/servlet/BuyServlet?id="+book.getId());
             out.write(book.getName()+"<a href='"+url+"' target='_blank'>购买</a><br/>");
         }
        
        
    }

    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request,response);
        
    }

}


class DB{
     private static Map<String,Book> map=new LinkedHashMap<String,Book>();
     static{    map.put("1",new Book("1","PHP开发","小王","19.63"));
                 map.put("2",new Book("2","javascript开发","小王","19.63"));
                 map.put("3",new Book("3","java开发","小王","19.63"));
                 map.put("4",new Book("4","html开发","小王","19.63"));
         }
    public static Map<String, Book> getMap() {
        return map;
    }
     
}
class Book implements Serializable{
    private String id;
    private String name;
    private String author;
    private String price;
    public Book() {
        
    }
    public Book(String id, String name, String author, String price) {
        super();
        this.id = id;
        this.name = name;
        this.author = author;
        this.price = price;
    }
    
    
    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 String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public String getPrice() {
        return price;
    }
    public void setPrice(String price) {
        this.price = price;
    }
    
    
}

 

BuyServlet

package cn.lyjs.session;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class BuyServlet extends HttpServlet {


    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id=request.getParameter("id");
        Book book=DB.getMap().get(id);
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out=response.getWriter();
        
        HttpSession session=request.getSession();
        List list=(List) session.getAttribute("list");
        if(list==null){
            list=new ArrayList();
            session.setAttribute("list", list);
        }
        list.add(book);
        //request.getRequestDispatcher("/servlet/ListCarServlet").forward(request, response);
        String url=response.encodeRedirectURL(request.getContextPath()+"/servlet/ListCarServlet");
        response.sendRedirect(url);
    }

    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request,response);
        
    }

}

ListCarServlet

package cn.lyjs.session;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ListCarServlet extends HttpServlet {


    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out=response.getWriter();
        
        HttpSession session=request.getSession(false);
        if(session==null){
            out.write("你没有购买商品");
            return;
        }
        out.write("你购买的商品<br/>");
        Book b=new Book();
        List<Book> list=(List<Book>) session.getAttribute("list");
        for(Book book:list){
            out.write(book.getName()+"<br/>");
        }
        
        
    }

    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doGet(request,response);
    }

}

 

posted @ 2015-10-21 14:53  好人难寻  阅读(186)  评论(0编辑  收藏  举报