jsp购物车代码(jsp网上购物代码及操作!)
亲爱的读者们,你是否对jsp购物车代码和jsp网上购物代码及操作!的相关问题感到困惑?别担心,今天我将为你解答这些问题,让你对此有更清晰的认识。
怎么用jsp的session对象编写购物车
肯定需要用javabean啊,如果要购买的话就把这个物存入到map类型的cart里面,再调用session.setAttribute方法把hashmap类型的cart放到session里面,然后在购物车那个页面取出购物车里的东西就行了,
DiscBean bean=data.getItem(itemid);这是选中物品的id
得到session对象
HttpSession session= request.getSession();
得到map类型的购物车
Map car=(Map)session.getAttribute("car");
if(car==null){
car=new HashMap();
session.setAttribute("car", car);
}
Set set=car.keySet();得到键的集合
Object[] bea=set.toArray();
boolean isNewDisc= true;
for(Object object: bea){
DiscItem discitem=(DiscItem)car.get(object);
String discitemid= discitem.getDiscBean().getItemID();
if(itemid.equals(discitemid)){
isNewDisc= false;
discitem.setNumber(discitem.getNumber()+1);
break;
}
}
if(isNewDisc){
car.put(itemid, new DiscItem(bean,1));
}
这个例子就是说我添加一本书的信息,如果是已经在购物车里了,就更新它的数量,如果没在购物车里,就把这个bean保存到购物车,并且数量设为一
如何用java和jsp做一个简单的购物车
页面jsp:
<%@pagelanguage="java"contentType="text/html;charset=utf-8"
pageEncoding="utf-8"%>
<%@taglibprefix="c"uri="
<%@tagliburi="
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""
<htmlxmlns="
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>易买网-首页</title>
<linktype="text/css"rel="stylesheet"rel="external nofollow" href="${pageContext.request.contextPath}/css/style.css"/>
<scripttype="text/javascript"src="${pageContext.request.contextPath}/js/jquery-2.1.1.js"></script>
<scripttype="text/javascript">
varcontextPath='${pageContext.request.contextPath}';
</script>
<scripttype="text/javascript"src="${pageContext.request.contextPath}/js/shopping.js"></script>
</head>
<body>
<jsp:includepage="top.jsp"/>
<divid="position"class="wrap">
您现在的位置:<arel="external nofollow" href="Home">易买网</a>>购物车
</div>
<divclass="wrap">
<divid="shopping">
<formaction=""method="post">
<table>
<tr>
<th>商品名称</th>
<th>商品价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
<c:forEachitems="${sessionScope.shopCar}"var="item"varStatus="status">
<trid="product_id_${item.proId}">
<tdclass="thumb"><imgsrc="${item.proImg}"height="50"width="30"/><arel="external nofollow" href="Product?action=view&entityId=${item.proId}">${item.proName}</a></td>
<tdclass="price"id="price_id_1">
<span><fmt:formatNumbervalue="${item.proPrice}"type="NUMBER"minFractionDigits="2"/></span>
<inputtype="hidden"value="${item.proPrice}"/>
</td>
<tdclass="number">
<dl>
<dt><spanonclick="sub('number_id_${item.proId}','${item.proId}')">-</span><inputid="number_id_${item.proId}"type="text"readonly="readonly"name="number"value="${item.proNum}"/><spanonclick="addNum('number_id_${item.proId}','${item.proId}')">+</span></dt>
</dl>
</td>
<tdclass="delete"><arel="external nofollow" href="javascript:deleteItem('product_id_${item.proId}','${item.proId}')">删除</a></td>
</tr>
</c:forEach>
</table>
<divclass="button"><inputtype="submit"value=""/></div>
</form>
</div>
</div>
<divid="footer">
Copyright©kaka292817678itjob远标培训.
</div>
</body>
</html>
页面关联的js自己去网上下载一个jquery
/*数量减少*/
functionsub(id,proId){
//购买数量的值
varnum=$('#'+id).val();
if(num>1){
$('#'+id).val(num-1);
}
edit(id,proId);
}
functionedit(id,proId){
varurl=contextPath+'/HomeCarManager';
//修改后的数量,购物明细的商品的id
num=$('#'+id).val();
$.post(url,{"num":num,"proId":proId},function(msg){
/*
if(msg=='true'){
alert('修改成功');
}else{
alert('修改失败');
}*/
});
}
/**
*数量增加
*@param{}id
*/
functionaddNum(id,proId){
//购买数量的值
varnum=$('#'+id).val();
$('#'+id).val(parseInt(num)+1);
edit(id,proId);
}
/**
*删除购物明细
*/
functiondeleteItem(trId,proId){
//
//console.log($("#"+trId));
//js删除页面节点
//$("#"+trId).remove();
varurl=contextPath+'/HomeCarManager';
$.post(url,{"proId":proId},function(msg){
if(msg=='true'){
//js删除页面节点
$("#"+trId).remove();
}
});
}
后台servlet1
packagecom.kaka.web;
importjava.io.IOException;
importjava.io.PrintWriter;
importjava.util.ArrayList;
importjava.util.List;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
/**
*购物车处理类
*@author@authorITJob远标培训
*
*/
importcom.kaka.entity.Items;
importcom.kaka.entity.Product;
importcom.kaka.service.ProductService;
importcom.kaka.service.impl.ProductServiceImpl;
publicclassHomeCarextendsHttpServlet{
privatestaticfinallongserialVersionUID=1L;
ProductServiceps=newProductServiceImpl();
@Override
protectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{
//获取商品的id
StringproId=req.getParameter("proId");
resp.setContentType("text/html;charset=UTF-8");
PrintWriterwriter=resp.getWriter();
if(null!=proId&&!"".equals(proId)){
//返回添加购物车成功
//System.out.println("============="+proId);
//根据商品的id查询商品
try{
IntegerpId=Integer.parseInt(proId);
Productproduct=ps.findProductById(pId);
if(null!=product){
//查询到了商品,将商品的相关参数构建一个购物明细放入到购物车
Itemsit=newItems();
it.setProId(product.getProId());
it.setProName(product.getProName());
it.setProPrice(product.getProPrice());
it.setProImg(product.getProImg());
//先判断session范围是否有购物车
List<Items>shopCar=(List<Items>)req.getSession().getAttribute("shopCar");
if(null==shopCar){
//购物车
shopCar=newArrayList<Items>();
}
//将商品加入到购物车之前,判断购物车中是否已经包含了该购物明细,如果包含了,只需要修改购买的数量
if(shopCar.contains(it)){
intindex=shopCar.indexOf(it);//寻找购物车中包含购物明细在购物车中位置
Itemsitems=shopCar.get(index);//获取购物车中存在的购物明细
items.setProNum(items.getProNum()+1);
}else{
shopCar.add(it);
}
//将购物车放入到session访问
req.getSession().setAttribute("shopCar",shopCar);
//返回
writer.print(true);
}else{
writer.print(false);
}
}catch(Exceptione){
e.printStackTrace();
writer.print(false);
}
}else{
writer.print(false);
}
writer.flush();
writer.close();
}
@Override
protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{
doPost(req,resp);
}
}
后台管理servlet
packagecom.kaka.web;
importjava.io.IOException;
importjava.io.PrintWriter;
importjava.util.ArrayList;
importjava.util.List;
importjavax.mail.FetchProfile.Item;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
/**
*购物车修改
*@authorITJob远标培训
*
*/
importcom.kaka.entity.Items;
importcom.kaka.entity.Product;
importcom.kaka.service.ProductService;
importcom.kaka.service.impl.ProductServiceImpl;
publicclassHomeCarManagerextendsHttpServlet{
privatestaticfinallongserialVersionUID=1L;
ProductServiceps=newProductServiceImpl();
@Override
protectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{
resp.setContentType("text/html;charset=UTF-8");
PrintWriterwriter=resp.getWriter();
//获取参数
StringproId=req.getParameter("proId");
Stringnum=req.getParameter("num");
if(null!=proId&&null!=num
&&!"".equals(proId)&&!"".equals(num)){
try{
IntegerpId=Integer.parseInt(proId);
FloatpNum=Float.parseFloat(num);
//根据商品的id获取对应的明细项
//先判断session范围是否有购物车
List<Items>shopCar=(List<Items>)req.getSession().getAttribute("shopCar");
for(Itemsit:shopCar){
if(it.getProId()==pId){
it.setProNum(pNum);
}
}
writer.print(true);
}catch(Exceptione){
e.printStackTrace();
}
}else{
//删除的操作
try{
IntegerpId=Integer.parseInt(proId);
//根据商品的id获取对应的明细项
//先判断session范围是否有购物车
List<Items>shopCar=(List<Items>)req.getSession().getAttribute("shopCar");
Itemsitems=null;
for(Itemsit:shopCar){
if(it.getProId()==pId){
items=it;
break;
}
}
if(null!=items){
shopCar.remove(items);
req.getSession().setAttribute("shopCar",shopCar);
}
writer.print(true);
}catch(Exceptione){
e.printStackTrace();
}
}
writer.flush();
writer.close();
}
@Override
protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{
doPost(req,resp);
}
}
jsp网上购物代码及操作!
1.index.jsp登陆界面:
<%@ page language="java" import="java.util.*" pageEncoding="GB2312"%>
<%
String path= request.getContextPath();
String basePath= request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%session.invalidate();%><%--销毁所有session对象--%>
<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" href="<%=basePath%>">
<title>购物车</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" href="styles.css">
-->
</head>
<body>
<center>
<hr>
请输入用户名,默认的为Guest
<form action="checklogin.jsp" mothod=get>
<table width="40%" border="1">
<tr bgcolor="#336600">
<td><div align="center"><font color="FFFFFF">用户登陆</font></div></td>
</tr>
<tr align="center" bgcolor="#CCCCCC">
<td>用户名:<input type="password" name="userID"></td>
</tr>
<tr align="center" bgcolor="#CCCCCC">
<td>口令:<input type="password" name="password"></td>
</tr>
<tr align="center" bgcolor="#CCCCCC">
<td><input type="submit" value="登陆"></td>
</tr>
</table>
</form>
</center>
</body>
</html>
2.checklogin.jsp登陆认证页面:
<%@ page language="java" import="java.util.*" pageEncoding="GB2312"%>
<%
String path= request.getContextPath();
String basePath= request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<jsp:useBean id="Car" class="web.Car" scope="session">
<jsp:setProperty property="*" name="Car"/>
</jsp:useBean>
<%session.setMaxInactiveInterval(900);%><%--设置session超时为30分--%>
<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" href="<%=basePath%>">
<title>My JSP'checklogin.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" href="styles.css">
-->
</head>
<body>
<%
String nextpage;
if(Car.getUserID().equals("Guest"))
nextpage="car.jsp";
else
nextpage="index.jsp";
%>
<jsp:forward page="<%=nextpage%>"></jsp:forward>
</body>
</html>
3.car.jsp购物车页面
<%@ page language="java" import="java.util.*" pageEncoding="GB2312"%>
<%
String path= request.getContextPath();
String basePath= request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ page import="java.util.*"%>
<%@ page import="web.Car"%>
<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" href="<%=basePath%>">
<title>购物车</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" href="styles.css">
-->
</head>
<body>
<br><%@ include file="header.jsp"%>
<hr>
<font size="2">
<jsp:useBean id="Car" class="web.Car" scope="session">
</jsp:useBean>
<p><font color="#804040" face="楷体_GB2312">
<strong>百货商场,请尽情的选购商品添加到购物车!</strong>
</font>
<%String str=response.encodeRedirectURL("add.jsp");%>
<form action="<%=str%>" method="post" name="form">
<select name="item" value="没选择">
<option value="TV">电视机</option>
<option value="apple">苹果</option>
<option value="coke">可口可乐</option>
<option value="milk">牛奶</option>
<option value="tea">茶叶</option>
</select>
<p><font color="#804040" face="楷体_GB2312">
输入购买的数量:
</font>
<input type="text" name="mount">
<p>
<input type="radio" name="unit" value="个">个
<input type="radio" name="unit" value="公斤">公斤
<input type="radio" name="unit" value="台">台
<input type="radio" name="unit" value="瓶">瓶<p>
<input type="submit" value="提交添加">
</form>
<p><font color="#804040" face="楷体_GB2312">你的购物车里有如下商品:</font>
<font color="#FF8040" size="2">
<%
Hashtable list=Car.list_h();
Enumeration enums=list.elements();
while(enums.hasMoreElements()){
String goods=(String) enums.nextElement();
byte b[]=goods.getBytes("ISO-8859-1");
goods=new String(b);
out.println("<br>"+goods);
}
%>
</font>
<% String strl=response.encodeRedirectURL("selectRemoveGoods.jsp");%>
<form action="<%=strl%>" method="post" name="form">
<input type="submit" value="修改购物车中的商品">
</form>
</font>
<%@ include file="tail.jsp"%>
</body>
</html>
4.add.jsp增加物品:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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>
<base rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" href="<%=basePath%>">
<title>购物车</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" href="styles.css">
-->
</head>
<body>
<%@ include file="header.jsp"%>
<hr>
<font size="2">
<jsp:useBean id="Car" class="web.Car" scope="session"></jsp:useBean><br>
<jsp:setProperty name="Car" property="*"/>
<%Car.add_h();%>
<font face="楷体_GB2312">
<font color="#FF8040" size="2">
<p>您的购物车有如下商品:
<%
Hashtable list=Car.list_h();
Enumeration enums=list.elements();
while(enums.hasMoreElements()){
String goods=(String) enums.nextElement();
byte b[]=goods.getBytes("ISO-8859-1");
goods=new String(b);
out.println("<br>"+goods);
}
%>
</font>
<%String str=response.encodeRedirectURL("car.jsp");%>
<br>
<form action="<%=str%>" method="post" neme="form">
<input type="submit" value="继续购物">
</form>
<%String strl=response.encodeRedirectURL("selectRemoveGoods.jsp");%>
<br>
<form action="<%=strl%>" method="post" neme="form">
<input type="submit" value="修改购物车中的物品">
</form>
</font>
</font>
<%@ include file="tail.jsp"%>
</body>
</html>
5.selectRemoveGoods.jsp选择删除商品:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path= request.getContextPath();
String basePath= request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ page import="java.util.*"%>
<%@ page import="web.Car"%>
<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" href="<%=basePath%>">
<title>购物</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" href="styles.css">
-->
</head>
<body>
<br><%@ include file="header.jsp"%>
<hr>
<jsp:useBean id="Car" class="web.Car" scope="session">
</jsp:useBean><br>
<p>选择从购物车中删除的物品:
<%String str=response.encodeRedirectURL("removeWork.jsp");%>
<form action="<%=str%>" method="post" name="form">
<select name="deleteitem" size="1">
<option value="TV">电视机</option>
<option value="apple">苹果</option>
<option value="coke">可口可乐</option>
<option value="milk">牛奶</option>
<option value="tea">茶叶</option>
</select>
<input type="submit" value="提交删除">
</form>
<font face="楷体_GB2312">
<font color="#FF8040" size="2">
<p>您的购物车有如下商品:
<%
Hashtable list=Car.list_h();
Enumeration enums=list.elements();
while(enums.hasMoreElements()){
String goods=(String) enums.nextElement();
byte b[]=goods.getBytes("ISO-8859-1");
goods=new String(b);
out.println("<br>"+goods);
}
%>
</font></font>
<%String strl=response.encodeRedirectURL("car.jsp");%>
<form action="<%=strl%>" method="post" neme="form">
<input type="submit" value="继续购物">
</form>
<%@include file="tail.jsp"%>
</body>
</html>
6.removeWork.jsp删除页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path= request.getContextPath();
String basePath= request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ page import="java.util.*"%>
<%@ page import="web.Car"%>
<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" href="<%=basePath%>">
<title>购物车</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" href="styles.css">
-->
</head>
<body>
<%@include file="header.jsp"%>
<hr>
<font size="2">
<jsp:useBean id="Car" class="web.Car" scope="session">
</jsp:useBean><br>
<%String str=response.encodeRedirectURL("removeWork.jsp");%>
<%String name=request.getParameter("deleteitem");
if(name==null)
name="";
byte c[]=name.getBytes("ISO-8859-1");
name=new String(c);
Car.dele_h(name);
out.println("您删除了货物"+name);%>
</font>
<font face="楷体_GB2312">
<font color="#FF8040" size="2">
<p>您的购物车有如下商品:
<%
Hashtable list=Car.list_h();
Enumeration enums=list.elements();
while(enums.hasMoreElements()){
String goods=(String) enums.nextElement();
byte b[]=goods.getBytes("ISO-8859-1");
goods=new String(b);
out.println("<br>"+goods);
}
%>
</font></font>
<%String strp=response.encodeRedirectURL("car.jsp");%>
<form action="<%=strp%>" method="post" neme="form">
<input type="submit" value="继续购物">
</form>
<%String strl=response.encodeRedirectURL("selectRemoveGoods.jsp");%>
<form action="<%=strl%>" method="post" neme="form">
<input type="submit" value="修改购物车中的物品">
</form>
</body>
</html>
7.header.jsp页面头部:
<%@ page language="java" import="java.util.*" pageEncoding="GB2312"%>
<center>
========================================================================<br>
购物车系统<br>
=======================================================================<br>
WELCOME!
<jsp:getProperty name="Car" property="userID"/>
当前时间是:
<%=new java.util.Date().toLocaleString()%>
<br>
</center>
8.tail页面尾部
<%@ page language="java" import="java.util.*" pageEncoding="GB2312"%>
<center>
<hr>
JSP+TOMCAT购物系统
</center>
9.Car.java类
package web;
import java.util.*;
import java.io.*;
public class Car implements Serializable{
Hashtable list=new Hashtable();//散列表,商品列表
String item="Welcome";
int mount=0;//商品数量
String unit=null;//商品单位
String userID;//用户
public void Car(){
}
public void setItem(String item){
this.item= item;
}
public void setMount(int mount){
this.mount= mount;
}
public void setUnit(String unit){
this.unit= unit;
}
public String getUserID(){
return userID;
}
public void setUserID(String userID){
this.userID= userID;
}
public Hashtable list_h(){
return list;
}
public void dele_h(String s){
list.remove(s);
}
public void add_h(){
String str="Name:"+item+"Mount:"+mount+"Unit:"+unit;
list.put(item, str);
}
}
好了,文章到此结束,希望可以帮助到大家。