AddItem.java
资源名称:store.zip [点击查看]
上传用户:qingshan
上传日期:2022-03-24
资源大小:9089k
文件大小:3k
源码类别:
Ajax
开发平台:
Java
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package servlet;
- import Entity.Item;
- 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;
- /**
- *
- * @author rincewind
- */
- public class AddItem extends HttpServlet {
- protected void processRequest(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("text/html;charset=UTF-8");
- PrintWriter out = response.getWriter();
- ArrayList<Item> items=new ArrayList();
- String name=request.getParameter("itemid"); //接受商品名称
- String num=request.getParameter("num"); //接受商品数 //将其转化为整型
- String price=request.getParameter("price");
- HttpSession session=request.getSession();
- String[] info=new String[4];
- Item item=new Item(); //用类封装
- item.setItemname(name);
- item.setPrice("1");
- item.setNum(num);
- try {
- if(session.getAttribute("items")==null){ //第一次购物
- items.add(item); //将商品添加到已经购物的商品中
- session.setAttribute("items",items);
- }else{ //以后添加商品
- items=(ArrayList<Item>) session.getAttribute("items");
- items.add(item);
- session.setAttribute("items",items);
- }
- int num1=Integer.parseInt(num);
- int p1=Integer.parseInt(price);
- int sum=num1*p1;
- String result="{name:'"+name+"',price:'"+price+"',num:'"+num+"',sum:'"+String.valueOf(sum)+"'}";
- out.print(result);
- }catch(Exception e){
- request.setAttribute("error", e.getMessage());
- out.print(e.getMessage());
- } finally {
- out.close();
- }
- }
- // <editor-fold defaultstate="collapsed" desc="HttpServlet 方法。单击左侧的 + 号以编辑代码。">
- /**
- * Handles the HTTP <code>GET</code> method.
- * @param request servlet request
- * @param response servlet response
- * @throws ServletException if a servlet-specific error occurs
- * @throws IOException if an I/O error occurs
- */
- @Override
- protected void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- processRequest(request, response);
- }
- /**
- * Handles the HTTP <code>POST</code> method.
- * @param request servlet request
- * @param response servlet response
- * @throws ServletException if a servlet-specific error occurs
- * @throws IOException if an I/O error occurs
- */
- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- processRequest(request, response);
- }
- /**
- * Returns a short description of the servlet.
- * @return a String containing servlet description
- */
- @Override
- public String getServletInfo() {
- return "Short description";
- }// </editor-fold>
- }