www.pudn.com > bookshop.zip > BuyServlet.java, change:2013-07-09,size:1903b


package com.tarena.web; 
 
import java.io.IOException; 
import java.io.PrintWriter; 
import java.util.ArrayList; 
 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import javax.servlet.http.HttpSession; 
 
import com.tarena.bean.Book; 
import com.tarena.bean.BookItem; 
import com.tarena.bean.Cart; 
import com.tarena.dao.BookDao; 
 
public class BuyServlet extends HttpServlet { 
 
	public void service(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException { 
		 
		request.setCharacterEncoding("utf-8"); 
        response.setContentType("text/html;charset=utf-8"); 
        String id  = request.getParameter("id"); 
       // System.out.println("该书的id是: "+id); 
         
        BookDao dao =new BookDao(); 
        Book book = dao.getBookById(Integer.parseInt(id)); 
        HttpSession session = request.getSession(); 
        Cart cart =(Cart)session.getAttribute("cart"); 
        int index = -1;//-1代表第一次购买   如果为1代表已经购买过该商品 
        if(cart==null){ 
        	cart = new Cart(); 
        	session.setAttribute("cart",cart); 
        	cart = (Cart)session.getAttribute("cart"); 
        }else{ 
        	ArrayList<BookItem> items = cart.getItems(); 
        	for(BookItem item:items){ 
        		if(item.getBook().getId() == Integer.parseInt(id)){ 
        			//items.add(new BookItem(1,book)); 
            	    index =1; 
            	    } 
        		} 
        	} 
        if(index==-1){ 
        	ArrayList<BookItem> items = cart.getItems(); 
        	items.add(new BookItem(1,book)); 
        } 
        PrintWriter out = response.getWriter(); 
        if(index == -1){ 
        	out.write("0");//代表购买成功 
        }else{ 
        	out.write("1");//代表购买已经购买过了 
        }  
	} 
}