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 products=new ArrayList();
	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 cart=(List) session.getAttribute(CART_ATTRIBUTE);
			if(cart==null){
				cart=new ArrayList();
				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("Products"+
		"

Products

"); write.println("
    "); //列出product列表 for(Product product:products){ write.println("
  • "+product.getName()+"("+currencyFormat.format(product.getPrice()) +") ("+"Details)"); } write.println("
"); write.println("View Cart"); write.println(""); } 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(""
					+"Product Details"
					+"

Product Details

" +"
"); write.println(""); write.println(""); write.println(""); write.println(""); write.println(""+"" +"" +"" +""); write.println(""); write.println("
Name:" +product.getName()+"
Description:" +product.getDescription()+"
" +"Product List" +"
"); write.println("
"); }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("Shopping Cart");
	     writer.println("Product List");
	     HttpSession session=req.getSession();
	     List cart=(List) 
	    		 session.getAttribute(CART_ATTRIBUTE);
	     if(cart!=null){
	    	 writer.println("");
	    	 writer.println(""
	    	 		 +""
	    			 +" "
	    			 +""
	    			 +"");
	    	 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(""
	    					 +""
	    					 +""
	    					 +"");
	    			 double subtotal=price*quantity;
	    			 writer.println("");
	    		 }
	    	 }
	    	 writer.println("");
	    	 writer.println("
QuantityProductPriceAmount
"+quantity+""+product.getName()+""+currencyFormat.format(price)+""+currencyFormat.format(subtotal)); total+=subtotal; writer.println("
" +"style='text-align:right'>" +"Total:" +currencyFormat.format(total) +"
"); } writer.println(""); } }

下面URL时调用应用程序的主页面:

http://localhost:8080/appShop/products     (appShop为web项目名称)



你可能感兴趣的:(JSP和Servlet学习指南)