这几天写了下JAVA写的COOKIE的DEMO。可能代码有点长,希望对需要的朋友有帮助。
框架:SPRINGMVC
[b]1、首先是购物车工具类 get set方法略[/b]
[b]2、购物车其中的一项(工具类)[/b]
[b]3、购物车的使用--ACTION类[/b]
[b]附、COOKIE工具类[/b]
框架:SPRINGMVC
[b]1、首先是购物车工具类 get set方法略[/b]
/**
* 购物车工具类
*/
public class Cart {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(Cart.class);
private List<CartItem> items = new ArrayList<CartItem>();
private HttpServletRequest request;
private double sumamount;//总计金额
private int sumnumb;//总计数量
public Cart() {
}
//增加
public void addItem(CartItem item) {
if (items.contains(item)) {// 如果购物项已经存在于购物车,累加其购买数量
for (CartItem cItem : items) {
if (cItem.equals(item)) {
cItem.setAmount(cItem.getAmount() + item.getAmount());
double price = cItem.getSpace().getPrice();
double totalamount = DataUtil.mul(price, cItem.getAmount(),1);
cItem.setTotalamount(totalamount);
break;
}
}
} else {
double price = item.getSpace().getPrice();
double totalamount = DataUtil.mul(price, item.getAmount(),1);
item.setTotalamount(totalamount);
items.add(item);
}
//计算总价
sumamount = this.getsumamount();
sumnumb = this.getsumnumb();
}
//删除
public void deleteItem(CartItem item) {
if (items.contains(item)){
items.remove(item);
}
//计算总价
sumamount = this.getsumamount();
sumnumb = this.getsumnumb();
}
//总价
public double getsumamount(){
double result = 0.0d;
for(CartItem cItem: items){
result = DataUtil.sum(result, cItem.getTotalamount());
}
return result;
}
//总数量
public int getsumnumb(){
int result = 0;
for(CartItem cItem: items){
result += cItem.getAmount();
}
return result;
}
/**
* 序列化
* @return
* @throws UnsupportedEncodingException
*/
public String serialize() throws UnsupportedEncodingException {
StringBuilder buffer = new StringBuilder();
for(int i = 0;i<items.size();i++){
String item = items.get(i).toString();
buffer.append(item);
buffer.append(";");
}
if (buffer.length() > 0)
buffer.deleteCharAt(buffer.length() - 1);
return buffer.toString();
}
/**
* 加载购物车
* @param ticketService
* @param content
* @throws UnsupportedEncodingException
*/
public void load(TicketService ticketService,String content) throws UnsupportedEncodingException {
items.clear();
if (content == null || "".equals(content))
return;
else {
try {
String[] itemsArry = content.split(";");
int sumnumb = 0;//总数量
double sumamount = 0.0;//总计
for (int i = 0; i < itemsArry.length; i++) {
String array = itemsArry[i];
String[] strarray = array.split(",");
int number = Integer.parseInt(strarray[0].split(":")[1]);
int id = Integer.parseInt(strarray[1].split(":")[1]);
//double price = Double.parseDouble(strarray[2].split(":")[1]);
CartItem item = new CartItem();
item.setAmount(number);
Space space = ticketService.findBySpaceId(id);
Ticket ticket = ticketService.findById(space.getTicketNo());
space.setTicketName(ticket.getTicketName());
item.setSpace(space);
item.setTotalamount(number, space.getPrice());//算小计
items.add(item);
sumnumb += number;
sumamount = DataUtil.sum(sumamount, item.getTotalamount());
}
this.setSumamount(sumamount);
} catch (Exception e) {
// TODO: handle exception
return;
}
}
}
//删除所有
public void deleteAll() {
items.clear();
}
}
[b]2、购物车其中的一项(工具类)[/b]
/**
* 购物车-一项
* @author shiaj
* Dec,2012
*/
@SuppressWarnings("serial")
public class CartItem implements java.io.Serializable{
private int amount = 1;//数量
private Space space;//商品实体类
private double totalamount;//小计
public CartItem(){}
public CartItem(int amount,Space space) {
this.amount = amount;
this.space = space;
}
/**
* 小计
* @param amount
* @param price
*/
public void setTotalamount(int amount,double price) {
this.totalamount = DataUtil.mul(amount, price, 2);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((space == null) ? 0 : space.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CartItem other = (CartItem) obj;
if(this.space.getSpaceNo().equals(other.getSpace().getSpaceNo())){
return true;
}
return false;
}
public String toString(){
StringBuffer string = new StringBuffer();
string.append("amount:" + amount + ",id:" + this.space.getSpaceNo() +
",price:" + this.space.getPrice());
return string.toString();
}
}
[b]3、购物车的使用--ACTION类[/b]
@Controller
public class OrderAct extends SessionCart{
@Autowired
private TicketService ticketService;
public static final String CART_ID = "cookie.cart.id";
/**
* 查看购物车
* @param request
* @param model
* @return
*/
@RequestMapping(value = "/shoppingcart.jhtml", method = RequestMethod.GET)
public String shoppingcart(HttpServletRequest request,ModelMap model){
String flag = this.getCartFlag(request);
if(flag == null || !flag.equals("havaReadCookie")){//COOKIE转SESSION
//读取COOKIE
Cart cart = this.getCart(request);
this.setShoppingCartSession(request, cart);
}
return "WEB-INF/t/cms/www/red/index/shoppingcart.html";
}
/**
* 加入购物车
* @param request
* @param response
* @param test
* @throws Exception
*/
@RequestMapping(value = "/addItem.jhtml")
public void addItem(HttpServletRequest request,
HttpServletResponse response,Space space,Integer amount) throws Exception {
System.out.println(space.getSpaceNo());
String flag = this.getCartFlag(request);
Cart cart = new Cart();
if(flag == null || !flag.equals("havaReadCookie")){//COOKIE转SESSION
//读取COOKIE
cart = this.getCart(request);
} else{//若SESSION存在 则直接读取SESSION
cart = this.getShoppingCartSession(request);
}
Space newspace = this.ticketService.findBySpaceId(space.getSpaceNo());
Ticket ticket = this.ticketService.findById(newspace.getTicketNo());
newspace.setTicketName(ticket.getTicketName());
CartItem item = new CartItem(amount,newspace);
cart.addItem(item);
//放入购物车
saveToCookie(response, cart);
this.setCartFlag(request, "havaReadCookie");
this.setShoppingCartSession(request, cart);
String msg;
msg = "{'success':false}";
ResponseUtils.renderJson(response, msg);
}
/**
* 删除某一项
* @param request
* @param response
* @param test
* @throws Exception
*/
@RequestMapping(value = "/delItem.jhtml")
public void Item(HttpServletRequest request,
HttpServletResponse response,Space space,Integer amount) throws Exception {
String flag = this.getCartFlag(request);
Cart cart = new Cart();
if(flag == null || !flag.equals("havaReadCookie")){//COOKIE转SESSION
//读取COOKIE
cart = this.getCart(request);
} else{//若SESSION存在 则直接读取SESSION
cart = this.getShoppingCartSession(request);
}
Space newtest = this.ticketService.findBySpaceId(space.getSpaceNo());
CartItem item = new CartItem(amount,newtest);
cart.deleteItem(item);
//放入购物车
saveToCookie(response, cart);
this.setCartFlag(request, "havaReadCookie");
this.setShoppingCartSession(request, cart);
String msg;
msg = "{'success':false}";
ResponseUtils.renderJson(response, msg);
}
/**
* 保存cookie
*/
private void saveToCookie(HttpServletResponse response, Cart cart)
throws Exception {
CookieUtils.addCookie(response, CART_ID + "01", cart.serialize());
}
/**
* 购物车的初始化
*
* @return CartService
*/
private Cart getCart(HttpServletRequest request) {
Cart cs = null;
try {
String cartStr = "";
cartStr = CookieUtils.findCookie(request, CART_ID + "01");
cs = new Cart();
if (cartStr != null && !"".equals(cartStr)) {
cs.load(ticketService,cartStr);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return cs;
}
}
[b]附、COOKIE工具类[/b]
public class CookieUtils {
public static final int MAX_AGE = 60 * 60 * 24 * 7;
/**
* 添加COOKIE
* @param response
* @param key
* @param value
* @throws UnsupportedEncodingException
*/
public static void addCookie(HttpServletResponse response, String key,
String value) throws UnsupportedEncodingException {
value = URLEncoder.encode(value, "utf-8");
Cookie cookie = new Cookie(key, value);
cookie.setMaxAge(MAX_AGE);
cookie.setPath("/");
response.addCookie(cookie);
}
/**
* 删除COOKIE
* @param response
* @param key
*/
public static void deleteCookie(HttpServletResponse response, String key) {
Cookie cookie = new Cookie(key, "");
cookie.setMaxAge(0);
cookie.setPath("/");
response.addCookie(cookie);
}
/**
* 查找COOKIE
* @param request
* @param key
* @return String
* @throws UnsupportedEncodingException
*/
public static String findCookie(HttpServletRequest request, String key)
throws UnsupportedEncodingException {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (key.equals(cookies[i].getName())) {
return URLDecoder.decode(cookies[i].getValue(), "utf-8");
}
}
}
return null;
}
}