㈠ 在做一個java web項目使用session保持購物車信息。
session表示當前會話,也就是說瀏覽關閉之後它就沒有了,切換用戶也會沒有,最好保存在資料庫中
㈡ 如何用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"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">
您現在的位置:<ahref="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="proct_id_${item.proId}">
<tdclass="thumb"><imgsrc="${item.proImg}"height="50"width="30"/><ahref="Proct?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"><ahref="javascript:deleteItem('proct_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.Proct;
importcom.kaka.service.ProctService;
importcom.kaka.service.impl.ProctServiceImpl;
{
=1L;
ProctServiceps=newProctServiceImpl();
@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);
Proctproct=ps.findProctById(pId);
if(null!=proct){
//查詢到了商品,將商品的相關參數構建一個購物明細放入到購物車
Itemsit=newItems();
it.setProId(proct.getProId());
it.setProName(proct.getProName());
it.setProPrice(proct.getProPrice());
it.setProImg(proct.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.Proct;
importcom.kaka.service.ProctService;
importcom.kaka.service.impl.ProctServiceImpl;
{
=1L;
ProctServiceps=newProctServiceImpl();
@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);
}
}
㈢ session+cookies實現購物車功能,javaweb開發
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'shop2.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");
Map<String,Integer> itm=(Map<String,Integer>)session.getAttribute("item");
if(itm==null){
itm=new HashMap<String,Integer>();
itm.put("電視", 1);
itm.put("蘋果", 0);
itm.put("香蕉", 1);
itm.put("衣服", 0);
}
String [] buy=request.getParameterValues("c");
for(String b:buy){
if(b.equals("電視")){
int num=itm.get("電視");
itm.put(b, num+1);
}
if(b.equals("蘋果")){
int num=itm.get(b);
itm.put(b, num+1);
}
if(b.equals("香蕉")){
int num=itm.get(b);
itm.put(b, num+1);
}
if(b.equals("衣服")){
int num=itm.get(b);
itm.put(b, num+1);
}
}
session.setAttribute("item", itm);
%>
你所購買的物品<br>
電視:<%=itm.get("電視") %>本<br>
蘋果:<%=itm.get("蘋果") %>個<br>
香蕉:<%=itm.get("香蕉") %>個<br>
衣服:<%=itm.get("衣服") %>件<br>
<p><a href="shop.jsp">再次購買</a></p>
</body>
</html>
下面是購買頁面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'shop.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" href="styles.css">
-->
</head>
<body>
歡迎光臨本店! <br>
<form action="shop2.jsp" method="post">
<input name="c" type="checkbox" value="電視" />電視
<input name="c" type="checkbox" value="蘋果" />蘋果
<input name="c" type="checkbox" value="香蕉" />香蕉
<input name="c" type="checkbox" value="衣服" />衣服
<img alt="dddd" src="<%=request.getAttribute("path")%>">
<p> <%=request.getAttribute("yy")%></p>
<input name="" type="submit" value="確認購買" />
</form>
</body>
</html>
下面是使用cookie的
添加Cookie
Cookie uname1=new Cookie("lname",username);
uname1.setMaxAge(24*3600);
Cookie upwd1=new Cookie("lpwd",pwd);
upwd1.setMaxAge(24*3600);
response.addCookie(uname1);
response.addCookie(upwd1);
添加session
session.setAttribute("log_name", username);
以下代碼是對cookie和session的數據操作!
<%
String uname="";
String upwd="";
Cookie[] cookies=request.getCookies(); //一request獲范圍獲取一個
cookie實例
if(cookies!=null){
for(Cookie c: cookies){
if("lname".equals(c.getName())){ //判斷cookie裡面的名字是否等於這
個
uname=c.getValue(); //如果等於就獲取它的值
}
if("lpwd".equals(c.getName())){
upwd=c.getValue();
}
}
String sql2="select * from member where username='"+uname+"'";
ResultSet rs2=null;
rs2=DBHelper.executeQuery(sql2);
boolean is=true;
while(rs2.next()){
String pp=rs2.getString("upwd");
if(pp.equals(upwd)){
is=false;
}
}
if(session.getAttribute("log_name")!=null){ //判斷是否有slog_name這
個session
uname=(String)session.getAttribute("log_name");
is=false;
}
if(is){
response.sendRedirect("index1.jsp");
}
}
%>
<%
application.setAttribute("log", uname);
%>
㈣ 怎麼刪除session裡面指定的值,這是一個購物車頁面,想刪除購物車里某個商品
Session.Remove("b");
㈤ 簡單的session購物車,就是不能統計買的具體商品的個數,高手看看哈,我是新手
您的購物車抄里襲有<%=((Map)session.getAttribute("cart")).size() %>種商品
你這個效果=map.size();
int i=0;
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
i++;
}
你買了i件商品
㈥ jsp 怎麼把存在session裡面的購物車訂單信息存到資料庫
<s:iterator value="dinnerServiceOuts1" id="dinner1" status="stat">
<s:hidden name="%{'dinnerServiceOuts1['+#stat.index+'].activeMode'}" value="%{dinnerServiceOuts1[#stat.index].activeMode}"/>
<s:hidden name="%{'dinnerServiceOuts1['+#stat.index+'].proctID'}" value="%{dinnerServiceOuts1[#stat.index].proctID}"/>
<s:hidden name="%{'dinnerServiceOuts1['+#stat.index+'].proctName'}" value="%{dinnerServiceOuts1[#stat.index].proctName}"/>
</s:iterator>
這樣寫才成否則你只能得到最後一個值
㈦ JSP 做網上商城系統時 在購物車上出了問題
你應該用一個集合類型,比如List來存儲你的商品信息。在每次添加新商品的時候,版就往這個集權合裡面添加商品信息!
例如:
List shoplist = new ArrayList();
request.getSession().setAttribute("c", shoplist );
這里做初始化的購物車。
如果添加了新商品,
List lis = request.getSession().setAttribute("c");
lis.add(cart)
request.getSession().setAttribute("c", lis);
這樣說LZ你明白了嗎?
㈧ 電子購物系統的 購物車 是如何實現的 是資料庫 還是cookie session 如何做 給個思路~
可以使用JavaBean建立一個商品類,用於保存商品的相關信息,再建立一個購物車,例如可以版用Collection保存商品,權用於保存所選擇的商品,然後可以使用form表單的select,將商品添加進去,提交後在結果頁面中獲取select選擇的結果,將所選的商品保存到購物車中,然後遍歷購物車,將商品保存到資料庫中
㈨ jsp如何清除購物車的session數據
session.remove("name");
㈩ 關於php 構建購物車裡面,用到session 書上有這樣一段程序
$_session=array_merge($_session['cart'],$_request['cart']);這句請注意,前面數組變數是$_session,而不是$_session['cart'],就是說這一句並沒有把$_request['cart']的內容添加到$_session['cart']中,版所以後面foreach段是必須的。權