路徑問題以及cookie詳解


1.路徑問題:

注意 .代表執行程序的文件夾路徑,在tomcat中也就是bin目錄,所以要用this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");得到絕對路徑;

代碼練習:

package com.http.path;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

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

public class PathDemo extends HttpServlet {

    public PathDemo() {
        super();
    }

    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        
        //給服務器使用的:   / 表示在當前web應用的根目錄(webRoot下)
        //request.getRequestDispatcher("/target.html").forward(request, response);
        
        //給瀏覽器使用的: /  表示在webapps的根目錄下
        //response.sendRedirect("/MyWeb/target.html");
        
        String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
        //this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
        System.out.println(path);
        Properties properties = new Properties();
        properties.load(new FileInputStream(new File(path)));
        
        String user = properties.getProperty("user");
        String passwd = properties.getProperty("passwd");
        System.out.println("user = " + user + "\npasswd = " + passwd);
    }

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

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the POST method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    public void init() throws ServletException {
        // Put your code here
    }

}

2.Cooke技術

2.1 特點

Cookie技術:會話數據保存在瀏覽器客戶端。

2.2 Cookie技術核心

Cookie類:用於存儲會話數據

 

1)構造Cookie對象

Cookie(java.lang.String name, java.lang.String value)

2)設置cookie

void setPath(java.lang.String uri)   :設置cookie的有效訪問路徑

void setMaxAge(int expiry)  設置cookie的有效時間

void setValue(java.lang.String newValue) :設置cookie的值

3)發送cookie到瀏覽器端保存

void response.addCookie(Cookie cookie)  : 發送cookie

4)服務器接收cookie

Cookie[] request.getCookies()  : 接收cookie

 

2.3 Cookie原理

1)服務器創建cookie對象,把會話數據存儲到cookie對象中。

new Cookie("name","value");

2 服務器發送cookie信息到瀏覽器

response.addCookie(cookie);

 

舉例: set-cookie: name=eric  (隱藏發送了一個set-cookie名稱的響應頭)

3)瀏覽器得到服務器發送的cookie,然后保存在瀏覽器端。

4)瀏覽器在下次訪問服務器時,會帶着cookie信息

    舉例: cookie: name=eric  (隱藏帶着一個叫cookie名稱的請求頭)

5)服務器接收到瀏覽器帶來的cookie信息

request.getCookies();

 

2.4 Cookie的細節

1void setPath(java.lang.String uri)   :設置cookie的有效訪問路徑。有效路徑指的是cookie的有效路徑保存在哪里,那么瀏覽器在有效路徑下訪問服務器時就會帶着cookie信息,否則不帶cookie信息。

 

2void setMaxAge(int expiry)  設置cookie的有效時間。

正整數:表示cookie數據保存瀏覽器的緩存目錄(硬盤中),數值表示保存的時間。

負整數:表示cookie數據保存瀏覽器的內存中。瀏覽器關閉cookie就丟失了!!

零:表示刪除同名的cookie數據

3Cookie數據類型只能保存非中文字符串類型的。可以保存多個cookie,但是瀏覽器一般只允許存放300Cookie,每個站點最多存放20Cookie,每個Cookie的大小限制為4KB

在下面查了下,cookie也可以存中文字符串,可以用URLEncoder類中的encode方法編碼,然后用URLDecoder.decode方法解碼

cookie的簡單練習:

package com.http.cookie;

import java.io.IOException;
import java.io.PrintWriter;

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

public class CookieDemo1 extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public CookieDemo1() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        Cookie cookie = new Cookie("name", "handsomecui");
        Cookie cookie2 = new Cookie("email", "handsomecui@qq.com");
        cookie2.setPath("/Test");
        //cookie.setMaxAge(10);//不會受到瀏覽器關閉的影響
        cookie.setMaxAge(-1);//cookie保存在瀏覽器內存,關閉移除
        //cookie.setMaxAge(0);//刪除同名cookie
        response.addCookie(cookie);
        response.addCookie(cookie2);
        System.out.println(request.getHeader("cookie"));
        Cookie[] cookies = request.getCookies();
        if(cookies == null){
            System.out.println("沒有cookie");
        }
        else{
            for(Cookie acookie : cookies){
                System.out.println(acookie.getName() + "是" + acookie.getValue());
            }
        }
        
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the POST method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

2.5 案例- 顯示用戶上次訪問的時間

代碼:

 

package com.http.cookie;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Date;

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

public class ShowTime extends HttpServlet {

    /**
     * Constructor of the object.
     */
    private int cnt = 0;
    public ShowTime() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    private String Isexist(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if(cookies == null){
            return null;
        }
        for(Cookie acookie:cookies){
            if("lasttime".equals(acookie.getName())){
                return acookie.getValue();
            }
        }
        return null;
    }
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        cnt++;
        response.setCharacterEncoding("gb2312");
        request.setCharacterEncoding("gb2312");
        
        response.getWriter().write("您好,這是您第" + cnt + "次訪問本站\n");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        
        String str = format.format(new Date());
        Cookie cookie = new Cookie("lasttime", str);
        response.addCookie(cookie);
        String lasttime = Isexist(request);
        if(lasttime != null){
            response.getWriter().write("您上次訪問的時間是:" + lasttime + "\n");
        }else{
            
        }
        response.getWriter().write("當前時間是:" + str + "\n");
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the POST method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

2.6 案例-查看用戶瀏覽器過的商品

思路:ListServlet展示商品列表,Detailservlet展示商品的詳細信息,最近瀏覽的商品,用一個hashset存儲MySet類,取出前三個不重復的即可,cookie存放最近瀏覽的商品編號,用逗號隔開;

product類:

package com.common.product;

import java.util.ArrayList;

public class Product {
    private static ArrayList<Product>arrayList;
    private int id;
    private String name;
    private String type;
    private double price;
    static{
        arrayList = new ArrayList<Product>();
        for(int i = 0; i < 10; i++){
            Product product = new Product(i + 1, "筆記本"+(i + 1), "LN00"+(i+1), 35+i);
            arrayList.add(product);
        }
    }
    public static ArrayList<Product> getArrayList() {
        return arrayList;
    }
    @Override
    public String toString() {
        return "id=" + id + ", name=" + name + ", type=" + type
                + ", price=" + price ;
    }
    public Product(int id, String name, String type, double price) {
        super();
        this.id = id;
        this.name = name;
        this.type = type;
        this.price = price;
    }
    public Product() {
        super();
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public Product getValueById(int p) {
        for(int i = 0; i < arrayList.size(); i++){
            if(arrayList.get(i).getId() == p){
                return arrayList.get(i);
            }
        }
        return null;
    }
    
}

MySet類:由編號和商品名構成,主要是為了hashset的去重與排序;

package com.common.tool;

import java.util.HashSet;

public class MySet{
    private int id;
    private String name;
    public int getId() {
        return id;
    }
    @Override
    public boolean equals(Object o) {
        // TODO Auto-generated method stub
        MySet myset = (MySet)o;
        return myset.getName().equals(this.getName());
    }
    @Override
    public int hashCode() {
        // TODO Auto-generated method stub
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public MySet(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }
    public MySet() {
        super();
    }
    
}

ListServlet:

package com.http.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;

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

import com.common.product.Product;


public class ListServlet extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public ListServlet() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        Product product = new Product();
        String html = "";
        html+=("<html>");
        html+=("<head>");
        html+=("<meta charset='utf-8'/>");
        
        html+=("<title>");
        html+=("商品列表");
        html+=("</title>");
        html+=("</head>");
        html+=("<body>");
        html+=("<table align='center' border='1'>");
        html+=("<tr>");
        html+=("<th>");
        html+=("編號");
        html+=("</th>");
        html+=("<th>");
        html+=("商品名稱");
        html+=("</th>");
        html+=("<th>");
        html+=("商品型號");
        html+=("</th>");
        html+=("<th>");
        html+=("商品價格");
        html+=("</th>");
        html+=("</tr>");
        ArrayList<Product> list = new Product().getArrayList();
        for(int i = 0; i < list.size(); i++){
            html+=("<tr>");
            html+=("<td>");
            html+=("" + list.get(i).getId());
            html+=("</td>");
            html+=("<td>");
            html+=("<a href = '"+ request.getContextPath() +"/DetailServlet"+"?id="+list.get(i).getId()+"'>" + list.get(i).getName() + "</a>");
            html+=("</td>");
            html+=("<td>");
            html+=(list.get(i).getType());
            html+=("</td>");
            html+=("<td>");
            html+=("" + list.get(i).getPrice());
            html+=("</td>");
            html+=("</tr>");
        }
        html+=("</table>");
        html+=("最近瀏覽過的商品: " + "<br/>");
        String recentview = null;
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for(Cookie cookie : cookies){
                if("RecentProduct".equals(cookie.getName())){
                    recentview = cookie.getValue();
                    break;
                }
            }
        }
        if(recentview != null){
            recentview = URLDecoder.decode(recentview, "UTF-8");
            String[] splits = recentview.split(",");
            for(String p : splits){
                html += (product.getValueById(Integer.parseInt(p)) + "<br/>");
            }
        }
        html+=("</body>");
        html+=("</html>");
        response.getWriter().write(html);
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the POST method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

DetailServlet

package com.http.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Stack;
import java.net.URLEncoder;

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

import com.common.product.Product;
import com.common.tool.MySet;

@SuppressWarnings("unused")
public class DetailServlet extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public DetailServlet() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        int id = Integer.parseInt(request.getParameter("id"));
        System.out.println(id);
        Product product = new Product().getValueById(id);
        String html = "";
        html+=("<html>");
        html+=("<head>");
        html+=("<meta charset='utf-8'/>");
        html+=("<title>");
        html+=("商品信息");
        html+=("</title>");
        html+=("</head>");
        html+=("<body>");
        html+=("<table align='center' border='1'>");
        
        html+=("<tr>");
        html+=("<th>");
        html+=("編號");
        html+=("</th>");
        html+=("<td>");
        html+=(id);
        html+=("</td>");
        html+=("</tr>");
        
        html+=("<tr>");
        html+=("<th>");
        html+=("商品名稱");
        html+=("</th>");
        html+=("<td>");
        html+=(product.getName());
        html+=("</td>");
        html+=("</tr>");
        
        html+=("<tr>");
        html+=("<th>");
        html+=("商品型號");
        html+=("</th>");
        html+=("<td>");
        html+=(product.getType());
        html+=("</td>");
        html+=("</tr>");
        
        html+=("<tr>");
        html+=("<th>");
        html+=("商品價格");
        html+=("</th>");
        html+=("<td>");
        html+=(product.getPrice());
        html+=("</td>");
        html+=("</tr>");
        
        html+=("</body>");
        html+=("</html>");
        Cookie acookie = null;
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for(Cookie cookie : cookies){
                if("RecentProduct".equals(cookie.getName())){
                    acookie = cookie;
                    break;
                }
            }
        }
        System.out.println(product.getName());
        if(acookie == null){
            acookie = new Cookie("RecentProduct", product.getId()+"");
            response.addCookie(acookie);
        }else{
            String[] splits = acookie.getValue().split(",");
            HashSet<MySet> set = new HashSet<MySet>();
            set.add(new MySet(0, product.getId()+""));
            for(int i = 0, j = 0; i < splits.length;i++){
                if((product.getId()+"").equals(splits[i]))
                    continue;
                j++;
                set.add(new MySet(j, splits[i]));
            }
            
            String value = "";
            Iterator<MySet> iterator = set.iterator();
            for(int i = 0; iterator.hasNext()&& i < 3; i++){
                MySet mySet = iterator.next();
                value += (mySet.getName() + ",");
            }
            acookie = new Cookie("RecentProduct", value);
            response.addCookie(acookie);
        }
        response.getWriter().write(html);
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the POST method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}


4 Session技術

4.1 引入

Cookie的局限:

1Cookie只能存字符串類型。不能保存對象

2)只能存非中文。

31Cookie的容量不超過4KB

 

如果要保存非字符串,超過4kb內容,只能使用session技術!!!

 

Session特點:

會話數據保存在服務器端。(內存中)

 

4.2 Session技術核心

HttpSession類:用於保存會話數據

 

1)創建或得到session對象

HttpSession getSession()  

HttpSession getSession(boolean create)  

2)設置session對象

void setMaxInactiveInterval(int interval)   設置session的有效時間

void invalidate()      銷毀session對象

java.lang.String getId()   得到session編號

3)保存會話數據到session對象

void setAttribute(java.lang.String name, java.lang.Object value)   保存數據

java.lang.Object getAttribute(java.lang.String name)   獲取數據

void removeAttribute(java.lang.String name) 清除數據

4.3 Session原理

問題: 服務器能夠識別不同的瀏覽者!!!

現象:

 

   前提: 在哪個session域對象保存數據,就必須從哪個域對象取出!!!!

瀏覽器1(s1分配一個唯一的標記:s001,s001發送給瀏覽器)

1)創建session對象,保存會話數據

HttpSession session = request.getSession();   --保存會話數據 s1

瀏覽器1 的新窗口(帶着s001的標記到服務器查詢,s001->s1,返回s1

1)得到session對象的會話數據

    HttpSession session = request.getSession();   --可以取出  s1

 

新的瀏覽器1(沒有帶s001,不能返回s1)

1)得到session對象的會話數據

    HttpSession session = request.getSession();   --不可以取出  s2

 

瀏覽器2(沒有帶s001,不能返回s1)

1)得到session對象的會話數據

    HttpSession session = request.getSession();  --不可以取出  s3

 

 

代碼解讀:HttpSession session = request.getSession();

 

1)第一次訪問創建session對象,給session對象分配一個唯一的ID,叫JSESSIONID

new HttpSession();

2)把JSESSIONID作為Cookie的值發送給瀏覽器保存

Cookie cookie = new Cookie("JSESSIONID", sessionID);

response.addCookie(cookie);

3)第二次訪問的時候,瀏覽器帶着JSESSIONIDcookie訪問服務器

4)服務器得到JSESSIONID,在服務器的內存中搜索是否存放對應編號的session對象。

if(找到){

return map.get(sessionID);

}

Map<String,HttpSession>]

 

 

<"s001", s1>

<"s001,"s2>

5)如果找到對應編號的session對象,直接返回該對象

6)如果找不到對應編號的session對象,創建新的session對象,繼續走1的流程

 

結論:通過JSESSIONcookie值在服務器找session對象!!!!!

4.4 Sesson細節

1java.lang.String getId()   得到session編號

2)兩個getSession方法:

getSession(true) / getSession()  : 創建或得到session對象。沒有匹配的session編號,自動創 建新的session對象。

getSession(false):              得到session對象。沒有匹配的session編號,返回null

3void setMaxInactiveInterval(int interval)   設置session的有效時間

session對象銷毀時間:

3.1 默認情況30分服務器自動回收

3.2 修改session回收時間

3.3 全局修改session有效時間

 

<!-- 修改session全局有效時間:分鍾 -->

<session-config>

<session-timeout>1</session-timeout>

</session-config>

 

3.4.手動銷毀session對象

void invalidate()      銷毀session對象

4)如何避免瀏覽器的JSESSIONIDcookie隨着瀏覽器關閉而丟失的問題

 

/**

 * 手動發送一個硬盤保存的cookie給瀏覽器

 */

Cookie c = new Cookie("JSESSIONID",session.getId());

c.setMaxAge(60*60);

response.addCookie(c);

代碼SessionDemo1

package com.http.cookie;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

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

public class SessionDemo1 extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public SessionDemo1() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        System.out.println("id = "+session.getId());
        session.setAttribute("name", "rose");
        session.setMaxInactiveInterval(60*60);
        Cookie cookie = new Cookie("JSESSIONID", session.getId());
        cookie.setMaxAge(60*60);
        response.addCookie(cookie);
        
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the POST method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

SessionDemo2:

package com.http.cookie;

import java.io.IOException;
import java.io.PrintWriter;

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 SessionDemo2 extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public SessionDemo2() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession(false);
        if(session != null){
            System.out.println(session.getAttribute("name"));
        }
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the POST method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

DeleteSession

package com.http.cookie;

import java.io.IOException;
import java.io.PrintWriter;

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 DeleteSession extends HttpServlet {

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession(false);
        if(session != null){
            session.invalidate();
            System.out.println("銷毀成功");
        }
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM