package shopping;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ShoppingServlet extends HttpServlet {
public void init(ServletConfig conf)throws ServletException{
super.init(conf);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
HttpSession session=request.getSession(false);
if(session==null){
response.sendRedirect("http://localhost:8080/error.html");
}
session.putValue("shoppingcart",null);
Vector buylist=(Vector)session.getValue("shopping.shoppingcart");
String action =request.getParameter("action");
if(!action.equals("CHECKOUT")){
if(action.equals("DELETE")){
//int d=Integer.parseInt(del);
String del=request.getParameter("delindex");
int d=(new Integer(del)).intValue();
buylist.removeElementAt(d);
}
else if(action.equals("ADD")){
boolean match=false;
Books aBook=getBook(request);
if(buylist==null){
buylist=new Vector();
buylist.addElement(aBook);
}
else
{
for(int i=0;i<buylist.size();i++){
Books book=(Books)buylist.elementAt(i);
if(book.getName().equals(aBook.getName())){
book.setQuantity(book.getQuantity()+aBook.getQuantity());
buylist.setElementAt(book, i);
match=true;
}
}
if(!match)
{
buylist.addElement(aBook);
}
}
}
session.putValue("shopping.shoppingcart", buylist);
String url="/EShop.jsp";
ServletContext sc=getServletContext();
RequestDispatcher rd=sc.getRequestDispatcher(url);
rd.forward(request,response);
}
else if(action.equals("CHECKOUT")){
float total=0;
for(int i=0;i<buylist.size();i++){
Books book=(Books)buylist.elementAt(i);
float price=book.getPrice();
int qty=book.getQuantity();
total+=(price*qty);
}
total+=0.005;
String amount=String.valueOf(total);
int n=amount.indexOf('.');
amount=amount.substring(0,n+3);
request.setAttribute("amount", amount);
String url="/Checkout.jsp";
ServletContext sc=getServletContext();
RequestDispatcher rd=sc.getRequestDispatcher(url);
rd.forward(request, response);
}
}
private Books getBook(HttpServletRequest req){
String myBook=req.getParameter("Book");
String qty=req.getParameter("qty");
StringTokenizer t=new StringTokenizer(myBook,"/");
String artist=t.nextToken();
String name=t.nextToken();
String price=t.nextToken();
Books book=new Books();
book.setArtist(artist);
book.setName(name);
book.setPrice(Float.parseFloat(price));
book.setQuantity(Integer.parseInt(qty));
return book;
}
}