1. 程式人生 > >Java——Web開發之Session的使用

Java——Web開發之Session的使用

Session會話:是基於Cookie的一種會話機制,資料存放在伺服器端。

  • Session建立:如果有在Servlet裡面呼叫了request.getSession()。
  • Session銷燬:session會話時間過期或者關閉伺服器就會被銷燬。設定會話時間過期時間到伺服器的web.xml裡設定,比如說tomcat的設定。

 

設定會話時間過期時間,這裡用tomcat為例子:在tomcat中,預設為30分鐘

 

Java裡使用Session時使用到的方法:

  • HttpSession session= request.getSession();
  • 得到會話ID:String id=session.getId();
  • 存資料:session.setAttribute(arg0, arg1);
  • 取資料:session.getAttribute(arg0);
  • 移除資料:session.removeAttribute(arg0);
  • 強制讓會話無效:session.invalidate();

方法使用案例:這個案例是模擬任務個數的開啟,清除所有任務。當點選超連結時,通過使用session的方式將資料臨時儲存到伺服器上,並進行下一次操作。

 

product_list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<a href="shopServlet?id=0"><h2>aa</h2></a><br>
	<a href="shopServlet?id=1"><h2>bb</h2></a><br>
	<a href="shopServlet?id=2"><h2>cc</h2></a><br>
	<a href="shopServlet?id=3"><h2>dd</h2></a><br>
	<a href="shopServlet?id=4"><h2>ee</h2></a><br>
	<a href="shopServlet?id=5"><h2>ff</h2></a><br>
</body>
</html>

shopServlet.java

package c.session;

import java.io.IOException;
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;

/**
 * Servlet implementation class shopServlet
 */
public class shopServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=utf-8");
		//1.獲取要新增工作列的id
		int id=Integer.parseInt(request.getParameter("id"));
		String[] names={"aa","bb","cc","dd","ee","ff"};
		String name=names[id];
		//2.獲取工作列存放任務的session  Map<String,Integer>  aa 3
		
		//把一個map物件存放到session裡面去,並且保證只儲存一次
		
		Map<String, Integer> map=(Map<String, Integer>)request.getSession().getAttribute("shop");
		//session裡面沒有存放過任何東西
		if(map==null){
			map=new LinkedHashMap<String, Integer>();
			request.getSession().setAttribute("shop", map);
		}
		//3.判斷工作列有沒有該任務
		if(map.containsKey(name)){
			map.put(name, map.get(name)+1);	//在原來的基礎上+1
		}else{
			map.put(name, 1);	//沒有該任務,置為1
		}
		
		//4.輸出介面(跳轉)
		response.getWriter().write("<a href='product_list.jsp'><h2>繼續執行</h2></a><br>");
		response.getWriter().write("<a href='shop.jsp'><h2>所有任務</h2></a>");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

 

shop.jsp

<%@page import="java.util.Map"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>您的工作列如下:</h2>

<%
	//1.先獲取到map
	Map<String,Integer> map=(Map<String,Integer>)session.getAttribute("shop");
	//2.遍歷map
	if(map!=null){
	for(String key: map.keySet()){
		int value=map.get(key);
%>
	<h3>名稱:<%=key %>   數量:<%=value %></h3><br>
<%		
	}
	}
 %>

<a href="clearshopServlet"><h4>清空工作列</h4></a>

</body>
</html>

clearshopServlet.java

package c.session;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class clearshopServlet
 */
public class clearshopServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session=request.getSession();
		
		//強制幹掉會話,裡面存放的任何資料都沒有了	session.invalidate();
		
		//從session中移除某一個數據
		session.removeAttribute("shop");
		response.sendRedirect("shop.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}