Servlet+jsp实现简单购物车

功能:BuyBook.jsp上输入所购书名,然后在下面就显示输入的书名,书名后有删除的链接,点删除就从购物车中删除。不涉及数据库。

文件:BuyBook.jsp  、BuyServlet.java ,Servletjsp是我的站点名,架构如下

Servlet+jsp实现简单购物车_第1张图片

(在MyEclipse下进行的测试,新建项目、servlet之类的就不说了)

代码:

BuyBook.jsp

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



   
    My JSP 'BuyBook.jsp' starting page   
 
  
 
  


   请输入书名:
  
  
  

  
  

   <%
      ArrayList gwc = (ArrayList)session.getAttribute("gwc");
      if(gwc!=null){
       for(int i=0;i         out.println(gwc.get(i));
        out.println("删除");
       }
      }
    %>
 

BuyServlet.java

package servlet;

import java.io.IOException;
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;

public class BuyServlet extends HttpServlet {

 public BuyServlet() {
  super();
 }

 public void destroy() {
  super.destroy(); // Just puts "destroy" string in log
  // Put your code here
 }

 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  String book = request.getParameter("book");
  String ope = request.getParameter("ope");
  HttpSession session = request.getSession();
  ArrayList gwc = (ArrayList)session.getAttribute("gwc");
  if(gwc == null){
   gwc = new ArrayList();
   session.setAttribute("gwc",gwc);
  }
  if(ope.equals("add")){
      gwc.add(book);//添加到购物车 
  }
  if(ope.equals("delete")){
   gwc.remove(book);
  }
  
  response.sendRedirect("/Servletjsp/BuyBook.jsp");
 }

 public void init() throws ServletException {
  // Put your code here
 }

}

web.xml


 xmlns="http://java.sun.com/xml/ns/j2ee" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 
    This is the description of my J2EE component
    This is the display name of my J2EE component
    BuyServlet
    servlet.BuyServlet
 


 
    BuyServlet
    /servlet/BuyServlet
 


 
    index.jsp
 


运行结果:

Servlet+jsp实现简单购物车_第2张图片

不足:输入中文,出来的是乱码。

你可能感兴趣的:(JSP,JAVA)