1. 程式人生 > >HttpSession物件的詳解與實戰操作

HttpSession物件的詳解與實戰操作

HttpSession物件:

     HttpSession是當一個使用者第一次訪問某個網站通過HttoServletRequest中呼叫getSession方法建立的

  1.    getSession有倆個過載方法:

           getSession()

           getSession(boolean create)

getSession(false) 方法返回當前的HttpSession ,若沒有,則返回null

getSession(true)方法返回當前的HttpSession,若沒有,則建立一個並返回,getSession(true)與getSession()方法一致

2.

HttpSession的setAttribute方法將一個值放在HttpSession物件裡

  void setAttribute(String name,Object value)

 注意:與網址重寫,隱藏域不同,放在HttpSession中的值是儲存在記憶體中的。會影響效能

value可以為任意java物件,只要他的類實現了java.io.Serializable介面即可,儲存的物件可以序列化成一個檔案儲存到資料庫中

 getAttribute方法可以用於獲取屬性

Object getAttribute(name)

getAttrubuteNames(),他返回一個Enumeration,迭代HttpSession物件的所有屬性

3

通過HttpSession中呼叫getId方法,可以獲取HttpSession的識別符號

String getId()

4

在預設情況下,HttpSession物件是在使用者靜默一段時間之後過期,setMaxInactiveInterval方法可以為個別HttpSession物件的Session設定一個期限

void setMaxInactiveInterval(int seconds)

如果這個方法傳入0,則改HttpSession將永遠不會過期,直到應用程式解除安裝或者Servlet容器關閉為止

下面舉個例子,這個類實現了一個小型的線上商城,裡面有四種商品。它允許使用者將商品新增到購物車中,並瀏覽其內容

//下面為產品類

package appShop;

public class Product {
	private int id;//產品id
	private String name;//產品名稱
	private String description;//產品描述
	private float price;//產品價格
	public Product(int id,String name,String description,float price){
		this.setId(id);
		this.setName(name);
		this.setDescription(description);
		this.setPrice(price);
	}
	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 getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public float getPrice() {
		return price;
	}
	public void setPrice(float price) {
		this.price = price;
	}

}
//下面為商城購物車類
package appShop;

public class ShoppingItem {
	private Product product;
	private int quantity;
	
	public ShoppingItem(Product product,int quantity){
		this.setProduct(product);
		this.setQuantity(quantity);
	}

	public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	public int getQuantity() {
		return quantity;
	}

	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}

}

//下面為主類

package appShop;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(name="ShoppingCartServlet",urlPatterns={"/products","/viewProductDetails","/addToCart","/viewCart"})
public class ShoppingCartServlet extends HttpServlet {
	private static final long serialVersionUID=-20L;
	private static final String CART_ATTRIBUTE="cart";
	
	private List<Product> products=new ArrayList<Product>();
	private NumberFormat currencyFormat=NumberFormat.getCurrencyInstance(Locale.US);
	//初始化四種產品包括其細節
	@Override
	public void init() throws ServletException {
		products.add(new Product(1,"TV","LOW-cost from China",159.95F));
		products.add(new Product(2,"Player","High quality stylish player",99.95F));
		products.add(new Product(3,"System","5 speaker hifi system with ipod",129.95F));
		products.add(new Product(4,"iPod player","can paly multiple formats",39.95F));
	}
        //URL都要呼叫doGet方法,依據URL的字尾啟動不同方法,產生不同頁面
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String uri=req.getRequestURI();
		if(uri.endsWith("/products")){
			sendProductList(resp);
		}else if(uri.endsWith("/viewProductDetails")){
			sendProductDetails(req,resp);
		}else if(uri.endsWith("/viewCart")){
			showCart(req,resp);
		}
		
	}
	
	//當點選buy時,則獲取其請求,將產品及其數量放入購物車
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		int quantity=0;
		int productId=0;
		try{
			productId=Integer.parseInt(req.getParameter("id"));
			quantity=Integer.parseInt(req.getParameter("quantity"));
		}catch(NumberFormatException e){}
		
		
		Product product=getProduct(productId);
		if(product!=null&&quantity>0){
			ShoppingItem shoppingItem=new ShoppingItem(product, quantity);
			HttpSession session=req.getSession();
			List<ShoppingItem> cart=(List<ShoppingItem>) session.getAttribute(CART_ATTRIBUTE);
			if(cart==null){
				cart=new ArrayList<ShoppingItem>();
				session.setAttribute(CART_ATTRIBUTE, cart);
			}
			cart.add(shoppingItem);
		}
		//若產品為空,則啟動產品列表
		sendProductList(resp);
	}
        //傳送產品的列表
	private void sendProductList(HttpServletResponse response) throws IOException{
		response.setContentType("text/html");
		PrintWriter write=response.getWriter();
		write.println("<html><head><title>Products</title>"+
		"</head><body><h2>Products</h2>");
		write.println("<ul>");
		//列出product列表
		for(Product product:products){
			write.println("<li>"+product.getName()+"("+currencyFormat.format(product.getPrice())
					+") ("+"<a href='viewProductDetails?id="+product.getId()+"'>Details</a>)");
		}
		write.println("</ul>");
		write.println("<a href='viewCart'>View Cart</a>");
		write.println("</body></html>");
				
	}
	private Product getProduct(int productId) {
		for(Product product:products){
			if(product.getId()==productId){
				return product;
			}
		}
		return null;
	}
        //傳送產品描述
	private void sendProductDetails(HttpServletRequest req,
			HttpServletResponse resp) throws IOException {
		resp.setContentType("text/html");
		PrintWriter write=resp.getWriter();
		int productId=0;
		try{
			productId=Integer.parseInt(req.getParameter("id"));
			
		}catch(NumberFormatException e){}
		
		Product product =getProduct(productId);
		
		if(product!=null){
			write.println("<html><head>"
					+"<title>Product Details</title></head>"
					+"<body><h2>Product Details</h2>"
					+"<form method='post' action='addToCart'>");
			write.println("<input type='hidden' name='id' "
					+"value=' "+productId+" '/>");
			write.println("<table>");
			write.println("<tr><td>Name:</td><td>"
					+product.getName()+"</td></tr>");
			write.println("<tr><td>Description:</td><td>"
					+product.getDescription()+"</td></tr>");
			write.println("<tr>"+"<tr>"
					+"<td><input name='quantity' ></td>"
					+"<td><input type='submit' value='buy'></td>"
					+"</tr>");
			write.println("<tr><td colspan='2'>"
					+"<a href='products'>Product List</a>"
					+"</td></tr>");
			write.println("</table>");
			write.println("</form></body>");
			
		}else{
			write.println("No product found");
		}
		
		
		
	}
       //展示購物車
	private void showCart(HttpServletRequest req, HttpServletResponse resp) throws IOException {
	     resp.setContentType("text/html");
	     PrintWriter writer=resp.getWriter();
	     writer.println("<html><head><title>Shopping Cart</title></head>");
	     writer.println("<body><a href='products'>Product List</a>");
	     HttpSession session=req.getSession();
	     List<ShoppingItem> cart=(List<ShoppingItem>) 
	    		 session.getAttribute(CART_ATTRIBUTE);
	     if(cart!=null){
	    	 writer.println("<table>");
	    	 writer.println("<tr>"
	    	 		 +"<td style='width:150px'>Quantity</td>"
	    			 +"<td style='width:150px'>Product</td> "
	    			 +"<td style='width:150px'>Price</td>"
	    			 +"<td>Amount</td></tr>");
	    	 double total=0.0;
	    	 for(ShoppingItem shoppingItem:cart){
	    		 Product product=shoppingItem.getProduct();
	    		 int quantity=shoppingItem.getQuantity();
	    		 if(quantity!=0){
	    			 float price=product.getPrice();
	    			 writer.println("<tr>"
	    					 +"<td>"+quantity+"</td>"
	    					 +"<td>"+product.getName()+"</td>"
	    					 +"<td>"+currencyFormat.format(price)+"</td>");
	    			 double subtotal=price*quantity;
	    			 writer.println("<td>"+currencyFormat.format(subtotal));
	    			 total+=subtotal;
	    			 writer.println("</tr>");
	    		 }
	    	 }
	    	 writer.println("<tr><td colspan='4'>"
	    			 +"style='text-align:right'>"
	    			 +"Total:"
	    			 +currencyFormat.format(total)
	    			 +"</td></tr>");
	    	 writer.println("</table>");
	    	 
	     }
		writer.println("</table></body></html>");
	}
	
	

}

下面URL時呼叫應用程式的主頁面:

http://localhost:8080/appShop/products     (appShop為web專案名稱)