HttpSession对象的详解与实战操作

来源:互联网 发布:淘宝代运营公司 编辑:程序博客网 时间:2024/06/06 08:44

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;//产品idprivate 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);//初始化四种产品包括其细节@Overridepublic 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的后缀启动不同方法,产生不同页面@Overrideprotected 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时,则获取其请求,将产品及其数量放入购物车@Overrideprotected 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项目名称)



2 0
原创粉丝点击