Servlet(二)--session管理--HttpSession

原创 2014年03月03日 17:16:03

示例代码:

package com.cdc.test;

public class Product {
	/** 产品id **/
	private int id;
	/** 产品名字 **/
	private String name;
	/*** 产品描述 **/
	private String description;
	/** 产品价钱 **/
	private float price;

	public Product(int id, String name, String description, float price) {
		this.id = id;
		this.name = name;
		this.description = description;
		this.price = 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 com.cdc.test;

public class ShoppingItem {

	private Product product;
	/***产品数量**/
    private int quantity;
	
    public ShoppingItem(Product product, int quantity) {
        this.product = product;
        this.quantity = 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 com.cdc.test;

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.CHINA);

	@Override
	public void init() throws ServletException {
		products.add(new Product(1, "电视机", "高清电视机", 159.95F));
		products.add(new Product(2, "电脑-台式机", "联想台式机", 99.95F));
		products.add(new Product(3, "笔记本电脑--联想", "联想笔记本", 129.95F));
		products.add(new Product(4, "华为--硬盘", "华为高端存储", 39.95F));
	}

	/*** Servlet默认会调用get方法 **/
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String uri = request.getRequestURI();
		if (uri.endsWith("/products")) {
			sendProductList(response);
		} else if (uri.endsWith("/viewProductDetails")) {
			sendProductDetails(request, response);
		} else if (uri.endsWith("viewCart")) {
			showCart(request, response);
		}
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// add to cart
		/** 产品的id **/
		int productId = 0;
		/** 产品的数量 **/
		int quantity = 0;
		try {
			productId = Integer.parseInt(request.getParameter("id"));
			quantity = Integer.parseInt(request.getParameter("quantity"));
		} catch (NumberFormatException e) {
		}

		Product product = getProduct(productId);
		if (product != null && quantity >= 0) {
			ShoppingItem shoppingItem = new ShoppingItem(product, quantity);
		/***获取session,并且查看里面是否有包含有一个CART_ATTRIBUTE的属性,如果有就把它添加到ShoppingItem里面,如果没有就创建一个.***/
			HttpSession session = request.getSession();
			@SuppressWarnings("unchecked")
			List<ShoppingItem> cart = (List<ShoppingItem>) session.getAttribute(CART_ATTRIBUTE);
			if (cart == null) {
				cart = new ArrayList<ShoppingItem>();
				/***将包含有产品数量和产品信息的集合添加到session---CART_ATTRIBUTE里面**/
				session.setAttribute(CART_ATTRIBUTE, cart);
			}
			cart.add(shoppingItem);
		}
		sendProductList(response);
	}

	private void sendProductList(HttpServletResponse response)
			throws IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter writer = response.getWriter();
		writer.println("<html><head><title>产品</title>"
				+ "</head><body><h2>产品</h2>");
		writer.println("<ul>");
		for (Product product : products) {
			writer.println("<li>" + product.getName() + "("
					+ currencyFormat.format(product.getPrice()) + ") ("
					+ "<a href='viewProductDetails?id=" + product.getId()
					+ "'>详情</a>)");
		}
		writer.println("</ul>");
		writer.println("<a href='viewCart'>查看购物车</a>");
		writer.println("</body></html>");

	}

	private Product getProduct(int productId) {
		for (Product product : products) {
			if (product.getId() == productId) {
				return product;
			}
		}
		return null;
	}

	private void sendProductDetails(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter writer = response.getWriter();
		int productId = 0;
		try {
			productId = Integer.parseInt(request.getParameter("id"));
		} catch (NumberFormatException e) {
		}
		Product product = getProduct(productId);

		if (product != null) {
			writer.println("<html><head>"
					+ "<title>产品详情</title></head>"
					+ "<body><h2>产品详情</h2>"
					+ "<form method='post' action='addToCart'>");
			writer.println("<input type='hidden' name='id' " + "value='"
					+ productId + "'/>");
			writer.println("<table>");
			writer.println("<tr><td>名称:</td><td>" + product.getName()
					+ "</td></tr>");
			writer.println("<tr><td>描述:</td><td>"
					+ product.getDescription() + "</td></tr>");
			writer.println("<tr>" + "<tr>"
					+ "<td><input name='quantity'/></td>"
					+ "<td><input type='submit' value='购买'/>" + "</td>"
					+ "</tr>");
			writer.println("<tr><td colspan='2'>"
					+ "<a href='products'>产品列表</a>" + "</td></tr>");
			writer.println("</table>");
			writer.println("</form></body>");
		} else {
			writer.println("没有此产品");
		}

	}

	private void showCart(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter writer = response.getWriter();
		writer.println("<html><head><title>购物车</title>" + "</head>");
		writer.println("<body><a href='products'>" + "产品列表</a>");
		/***获取在doPost()里面设置到session里面的值**/
		HttpSession session = request.getSession();
		@SuppressWarnings("unchecked")
		List<ShoppingItem> cart = (List<ShoppingItem>) session.getAttribute(CART_ATTRIBUTE);
		if (cart != null) {
			writer.println("<table>");
			writer.println("<tr><td style='width:150px'>数量" + "</td>"
					+ "<td style='width:150px'>产品</td>"
					+ "<td style='width:150px'>单价</td>"
					+ "<td>总额</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>");
					writer.println("<td>" + quantity + "</td>");
					writer.println("<td>" + product.getName() + "</td>");
					writer.println("<td>" + currencyFormat.format(price)
							+ "</td>");
					double subtotal = price * quantity;

					writer.println("<td>" + currencyFormat.format(subtotal)
							+ "</td>");
					total += subtotal;
					writer.println("</tr>");
				}
			}
			writer.println("<tr><td colspan='4' " + "style='text-align:right'>"
					+ "合计:" + currencyFormat.format(total) + "</td></tr>");
			writer.println("</table>");
		}
		writer.println("</table></body></html>");

	}
}


相关文章推荐

替换Servlet容器的HttpSession实现集群中Session共享(With Redis)

本文是我个人在开发web-security 安全框架中使用的方案。 在Web Server集群环境中需要实现 session 共享,一个很好的方法就是将 session 数据存放至 Redis 中。...

javax.servlet.http.HttpSession session用法详解

HttpSession类它提供了setAttribute()和getAttribute()方法存储和检索对象。 HttpSession提供了一个会话ID关键字,一个参与会话行为的客户端在同一会话...

关于Session(javax.servlet.HttpSession)持久化----为什么实体类需要实现序列化接口

为什么需要持久化?     客户端访问了某个能开启会话功能的资源,web服务器就会创建一个与该客户端对应的HttpSession对象,每个HttpSession对象都要占用一定的内存空间。如果在某一...

Servlet--浅析会话管理之Cookie、URL重写、HttpSession原理

平常我们在浏览网页的时候,会有一些网站要求我们进行登录,当我们成功登录之后,会发现我们所浏览的所有相关网页都不再需要我们重新登录,这是为什么呢。还有当我们在电商平台进行购物的时候,我们虽然是在同一家电...

[Servlet&JSP] HttpSession会话管理

我们可以将会话期间必须共享的资料保存在HttpSession中,使之成为属性。如果用户关掉浏览器接受Cookie的功能,HttpSession也可以改用URL重写的方式继续其会话管理功能。HttpSe...

servlet(二)--session管理---cookie

servlet--cookie import java.io.IOException; import java.io.PrintWriter; import javax.servlet.Servlet...

Servlet学习(二)__session管理__隐藏域

Servlet学习(二)__session管理__隐藏域 下面的示例通过隐藏域传递一个id值,修改某个值。 一.javabean代码. package com.cdc.servlettest.b...

Java Web基础知识之Servlet(3):Session管理

Session 管理是Web应用开发中的一个重要的内容,其实每天我们浏览网站,网站的后台都是通过这门技术来记录我们的浏览状态,最典型的就是登录,每次你在网站上登录一次,当跳转到该网站的任何其他页面都不...

笔记之Servlet的会话管理技术(cookie、session)(应用:用户自动登录、防表单重复提交)

会话管理: cookie 和Session都是Servlet技术 会话:从浏览器打开到关闭的访问过程。 会话管理:是实现多个WEB页面(超链接)的数据共享。典型应用:购买页面的数据和支付页面的数据...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Servlet(二)--session管理--HttpSession
举报原因:
原因补充:

(最多只允许输入30个字)