package com.restrant.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.RequestDispatcher;
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.restrant.entity.CartItemBean;
import com.restrant.entity.FoodBean;
public class AddFoodToCart extends HttpServlet {
/**
* Constructor of the object.
*/
public AddFoodToCart() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
request.setCharacterEncoding("GBK");
HttpSession session =request.getSession(false);
String id=request.getParameter("id");
if(id!=null){
int foodid=Integer.parseInt(id);
List<FoodBean> foodList = (List<FoodBean>) session
.getAttribute("FoodList");
for (int i = 0; i < foodList.size(); i++) {
FoodBean currentfood = (FoodBean) foodList.get(i);
if (currentfood.getFoodId() == foodid) {
session.setAttribute("foodToAdd", currentfood);
break;
}}
}
Map cart=(Map)session.getAttribute("cart");
FoodBean food=(FoodBean)session.getAttribute("foodToAdd");
RequestDispatcher dispatcher;
if(cart==null){
cart=new HashMap();
session.setAttribute("cart", cart);
}
CartItemBean cartItem=(CartItemBean)cart.get(food.getFoodId());
if(cartItem!=null){
cartItem.setQuantity(cartItem.getQuantity()+1);
}else{
cart.put(food.getFoodId(), new CartItemBean(food,1));
// dispatcher=request.getRequestDispatcher("/ch01/shopcart.jsp");
// dispatcher.forward(request, response);
}response.sendRedirect("/restrant/ch01/shopcart.jsp");
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}