功能:BuyBook.jsp上输入所购书名,然后在下面就显示输入的书名,书名后有删除的链接,点删除就从购物车中删除。不涉及数据库。
文件:BuyBook.jsp 、BuyServlet.java ,Servletjsp是我的站点名,架构如下
(在MyEclipse下进行的测试,新建项目、servlet之类的就不说了)
代码:
BuyBook.jsp
<%@ page language="java" imp
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'BuyBook.jsp' starting page</title>
</head>
<body>
<form act
请输入书名:
<input name="ope" type="hidden" value="add" />
<input name="book" />
<br/>
<input type="submit" value="add to cart" />
</form>
<%
ArrayList gwc = (ArrayList)session.getAttribute("gwc");
if(gwc!=null){
for(int i=0;i<gwc.size();i++){
out.println(gwc.get(i));
out.println("<a href=/Servletjsp/servlet/BuyServlet?ope=delete&book="+gwc.get(i)+">删除</a>");
}
}
%>
</body>
</html>
BuyServlet.java
package servlet;
imp
imp
imp
imp
imp
imp
imp
public class BuyServlet extends HttpServlet {
public BuyServlet() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your co
}
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 co
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
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">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>BuyServlet</servlet-name>
<servlet-class>servlet.BuyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BuyServlet</servlet-name>
<url-pattern>/servlet/BuyServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
运行结果:
不足:输入中文,出来的是乱码。