https://blog.csdn.net/hanhanwanghaha宝藏女孩 欢迎您的关注!
欢迎关注微信公众号:宝藏女孩的成长日记
如有转载,请注明出处(如不注明,盗者必究)
这周真的太忙了,就连写日记和更博洗头发的时间都没有,还好已经收到满意的结果。
现在开始要完善项目了,哈哈哈,和我的小粉丝们一起加油!冲冲冲!!!
项目前面几部分:
连接真机开发安卓(Android)移动app MUI框架——混合式开发(一) (敲详细)
连接真机开发安卓(Android)移动app MUI框架——混合式开发(二) 带你项目开发(最新版)
连接真机开发安卓(Android)移动app MUI框架——混合式开发(三) (连接后端)
连接真机开发安卓(Android)移动app MUI框架 添加购物车等——混合式开发(四)
今日主题:冲冲冲
- 一、完善购物车页面
- 二、完善继续购物(按钮)
- 三、添加去结算按钮功能
- 四、确认下单
- 五、显示我的订单
- 六、退出系统
一、完善购物车页面
原来的main.html
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Hello MUI</title><meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="black"><link rel="stylesheet" href="css/mui.min.css"><style>html,body {background-color: #efeff4;}</style></head><body><header class="mui-bar mui-bar-nav"><a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a><h1 id="title" class="mui-title">欢迎来到甜甜屋</h1></header><nav class="mui-bar mui-bar-tab"><a id="defaultTab" class="mui-tab-item mui-active" href="index.html"><span class="mui-icon mui-icon-home"></span><span class="mui-tab-label">首页</span></a><a class="mui-tab-item" href="prolist.html"><span class="mui-icon mui-icon-email"><span class="mui-badge">9</span></span><span class="mui-tab-label">商品列表</span></a><a class="mui-tab-item" href="car.html"><span class="mui-icon mui-icon-contact"><span class="mui-badge">9</span></span></span><span class="mui-tab-label">购物车</span></a><a class="mui-tab-item" href="my.html"><span class="mui-icon mui-icon-gear"></span><span class="mui-tab-label">我的</span></a></nav><script src="js/mui.min.js"></script><script type="text/javascript" charset="utf-8">//mui初始化mui.init();var subpages = ['index.html', 'prolist.html', 'car.html', 'my.html'];var subpage_style = {top: '45px',bottom: '51px'};var aniShow = {};//创建子页面,首个选项卡页面显示,其它均隐藏;mui.plusReady(function() {var self = plus.webview.currentWebview();for (var i = 0; i < 4; i++) {var temp = {};var sub = plus.webview.create(subpages[i], subpages[i], subpage_style);if (i > 0) {sub.hide();}else{temp[subpages[i]] = "true";mui.extend(aniShow,temp);}self.append(sub);}});//当前激活选项var activeTab = subpages[0];var title = document.getElementById("title");//选项卡点击事件mui('.mui-bar-tab').on('tap', 'a', function(e) {var targetTab = this.getAttribute('href');if (targetTab == activeTab) {return;}//更换标题title.innerHTML = this.querySelector('.mui-tab-label').innerHTML;//显示目标选项卡//若为iOS平台或非首次显示,则直接显示if(mui.os.ios||aniShow[targetTab]){plus.webview.show(targetTab);}else{//否则,使用fade-in动画,且保存变量var temp = {};temp[targetTab] = "true";mui.extend(aniShow,temp);plus.webview.show(targetTab,"fade-in",300);}//隐藏当前;plus.webview.hide(activeTab);//更改当前活跃的选项卡activeTab = targetTab;});//自定义事件,模拟点击“首页选项卡”document.addEventListener('gohome', function() {var defaultTab = document.getElementById("defaultTab");//模拟首页点击mui.trigger(defaultTab, 'tap');//切换选项卡高亮var current = document.querySelector(".mui-bar-tab>.mui-tab-item.mui-active");if (defaultTab !== current) {current.classList.remove('mui-active');defaultTab.classList.add('mui-active');}});</script></body></html>
现在我们要实现“点击购物车,跳到购物车页面”的功能
在第34行将购物车取id为car
添加自定义事件
在proview.html中触发
现在我们在商品明细中点击添加购物车就可以直接跳到购物车页面了
但是还是有个问题就是我们要刷新购物车页面
因此要添加一个刷新的事件
在car.html中添加此刷新代码
在proview.html中写触发事件
二、完善继续购物(按钮)
原main.html
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Hello MUI</title><meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="black"><link rel="stylesheet" href="css/mui.min.css"><style>html,body {background-color: #efeff4;}</style></head><body><header class="mui-bar mui-bar-nav"><a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a><h1 id="title" class="mui-title">欢迎来到甜甜屋</h1></header><nav class="mui-bar mui-bar-tab"><a id="defaultTab" class="mui-tab-item mui-active" href="index.html"><span class="mui-icon mui-icon-home"></span><span class="mui-tab-label">首页</span></a><a class="mui-tab-item" href="prolist.html"><span class="mui-icon mui-icon-email"><span class="mui-badge">9</span></span><span class="mui-tab-label">商品列表</span></a><a class="mui-tab-item" href="car.html"><span class="mui-icon mui-icon-contact"></span><span class="mui-tab-label">购物车</span></a><a class="mui-tab-item" href="my.html"><span class="mui-icon mui-icon-gear"></span><span class="mui-tab-label">我的</span></a></nav><script src="js/mui.min.js"></script><script type="text/javascript" charset="utf-8">//mui初始化mui.init();var subpages = ['index.html', 'prolist.html', 'car.html', 'my.html'];var subpage_style = {top: '45px',bottom: '51px'};var aniShow = {};//创建子页面,首个选项卡页面显示,其它均隐藏;mui.plusReady(function() {var self = plus.webview.currentWebview();for (var i = 0; i < 4; i++) {var temp = {};var sub = plus.webview.create(subpages[i], subpages[i], subpage_style);if (i > 0) {sub.hide();}else{temp[subpages[i]] = "true";mui.extend(aniShow,temp);}self.append(sub);}});//当前激活选项var activeTab = subpages[0];var title = document.getElementById("title");//选项卡点击事件mui('.mui-bar-tab').on('tap', 'a', function(e) {var targetTab = this.getAttribute('href');if (targetTab == activeTab) {return;}//更换标题title.innerHTML = this.querySelector('.mui-tab-label').innerHTML;//显示目标选项卡//若为iOS平台或非首次显示,则直接显示if(mui.os.ios||aniShow[targetTab]){plus.webview.show(targetTab);}else{//否则,使用fade-in动画,且保存变量var temp = {};temp[targetTab] = "true";mui.extend(aniShow,temp);plus.webview.show(targetTab,"fade-in",300);}//隐藏当前;plus.webview.hide(activeTab);//更改当前活跃的选项卡activeTab = targetTab;});//自定义事件,模拟点击“首页选项卡”document.addEventListener('gohome', function() {var defaultTab = document.getElementById("defaultTab");//模拟首页点击mui.trigger(defaultTab, 'tap');//切换选项卡高亮var current = document.querySelector(".mui-bar-tab>.mui-tab-item.mui-active");if (defaultTab !== current) {current.classList.remove('mui-active');defaultTab.classList.add('mui-active');}});</script></body></html>
在main中添加id为prolist
在main.html中添加自定义事件
完整的main.html
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Hello MUI</title><meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="black"><link rel="stylesheet" href="css/mui.min.css"><style>html,body {background-color: #efeff4;}</style></head><body><header class="mui-bar mui-bar-nav"><a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a><h1 id="title" class="mui-title">欢迎来到甜甜屋</h1></header><nav class="mui-bar mui-bar-tab"><a id="defaultTab" class="mui-tab-item mui-active" href="index.html"><span class="mui-icon mui-icon-home"></span><span class="mui-tab-label">首页</span></a><a id="prolist" class="mui-tab-item" href="prolist.html"><span class="mui-icon mui-icon-email"><span class="mui-badge">9</span></span><span class="mui-tab-label">商品列表</span></a><a id="car" class="mui-tab-item" href="car.html"><span class="mui-icon mui-icon-contact"><span class="mui-badge">9</span></span></span><span class="mui-tab-label">购物车</span></a><a class="mui-tab-item" href="my.html"><span class="mui-icon mui-icon-gear"></span><span class="mui-tab-label">我的</span></a></nav><script src="js/mui.min.js"></script><script type="text/javascript" charset="utf-8">//mui初始化mui.init();var subpages = ['index.html', 'prolist.html', 'car.html', 'my.html'];var subpage_style = {top: '45px',bottom: '51px'};var aniShow = {};//创建子页面,首个选项卡页面显示,其它均隐藏;mui.plusReady(function() {var self = plus.webview.currentWebview();for (var i = 0; i < 4; i++) {var temp = {};var sub = plus.webview.create(subpages[i], subpages[i], subpage_style);if (i > 0) {sub.hide();}else{temp[subpages[i]] = "true";mui.extend(aniShow,temp);}self.append(sub);}});//当前激活选项var activeTab = subpages[0];var title = document.getElementById("title");//选项卡点击事件mui('.mui-bar-tab').on('tap', 'a', function(e) {var targetTab = this.getAttribute('href');if (targetTab == activeTab) {return;}//更换标题title.innerHTML = this.querySelector('.mui-tab-label').innerHTML;//显示目标选项卡//若为iOS平台或非首次显示,则直接显示if(mui.os.ios||aniShow[targetTab]){plus.webview.show(targetTab);}else{//否则,使用fade-in动画,且保存变量var temp = {};temp[targetTab] = "true";mui.extend(aniShow,temp);plus.webview.show(targetTab,"fade-in",300);}//隐藏当前;plus.webview.hide(activeTab);//更改当前活跃的选项卡activeTab = targetTab;});//自定义事件,模拟点击“首页选项卡”document.addEventListener('gohome', function() {var defaultTab = document.getElementById("defaultTab");//模拟首页点击mui.trigger(defaultTab, 'tap');//切换选项卡高亮var current = document.querySelector(".mui-bar-tab>.mui-tab-item.mui-active");if (defaultTab !== current) {current.classList.remove('mui-active');defaultTab.classList.add('mui-active');}});document.addEventListener('goprolist', function() {var prolist = document.getElementById("prolist");//模拟首页点击mui.trigger(prolist, 'tap');//切换选项卡高亮var current = document.querySelector(".mui-bar-tab>.mui-tab-item.mui-active");if (prolist !== current) {current.classList.remove('mui-active');prolist.classList.add('mui-active');}});document.addEventListener('gocar', function() {var car = document.getElementById("car");mui.trigger(car, 'tap');//切换选项卡高亮var current = document.querySelector(".mui-bar-tab>.mui-tab-item.mui-active");if (car !== current) {current.classList.remove('mui-active');car.classList.add('mui-active');}});</script></body></html>
在car.html有如下触发事件
完成的效果是这样的
三、添加去结算按钮功能
原login.html
<!doctype html>
<html><head><meta charset="UTF-8"><title></title><meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /><link href="css/mui.min.css" rel="stylesheet" /><style type="text/css"></style></head><body><header class="mui-bar mui-bar-nav"><a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a><h1 class="mui-title">登录</h1></header><div class="mui-content"><form class="mui-input-group"><div class="mui-input-row"><label>用户名</label><input type="text" id="tbnusername" class="mui-input-clear" value="杰子" placeholder="用户名"></div><div class="mui-input-row"><label>密码</label><input type="text" id="tbnpassword" class="mui-input-clear" value="123" placeholder="密码"></div><div class="mui-input-row"><input value="登录" type="button" class="mui-btn-block" id="btnlogin" /></div><div style="height: 50px; text-align: center; line-height: 50px;"><span id="btnreg">注册账号</span>|<span id="">忘记密码</span></div></form></div><script src="js/mui.min.js"></script><script type="text/javascript">mui.init();document.getElementById("btnreg").addEventListener("tap",function(){console.log(11);mui.openWindow({url:"reg.html",id:"reg.html"});});document.getElementById("btnlogin").addEventListener("tap",function(){var vusername=document.getElementById("tbnusername").value;var vpassword=document.getElementById("tbnpassword").value; var requrl="http://192.168.43.242:8080/SweetyManage/JavaApi";localStorage.setItem("requrl",requrl);mui.ajax(requrl,{data:{rnum:"2",username:vusername,password:vpassword},dataType:'json',//服务器返回json格式数据type:'post',//HTTP请求类型timeout:10000,//超时时间设置为10秒;headers:{'Content-Type':'application/x-www-form-urlencoded'},success:function(data){console.log(JSON.stringify(data));if(data==null||data==""){mui.toast("用户名或者密码错误!");}else{console.log(data[0].id);mui.toast("登录成功!");localStorage.setItem("id",data[0].id);mui.openWindow({url:"main.html",id:"main"});} }});});</script></body></html>
点击这个按钮,我们可以定位到收货人,这里需要收货人的名字,电话和地址
在login.html中添加下面三项
表示:登录成功之后就把当前人的信息保存在localStorage中
完整的login.html
<!doctype html>
<html><head><meta charset="UTF-8"><title></title><meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /><link href="css/mui.min.css" rel="stylesheet" /><style type="text/css"></style></head><body><header class="mui-bar mui-bar-nav"><a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a><h1 class="mui-title">登录</h1></header><div class="mui-content"><form class="mui-input-group"><div class="mui-input-row"><label>用户名</label><input type="text" id="tbnusername" class="mui-input-clear" value="杰子" placeholder="用户名"></div><div class="mui-input-row"><label>密码</label><input type="text" id="tbnpassword" class="mui-input-clear" value="123" placeholder="密码"></div><div class="mui-input-row"><input value="登录" type="button" class="mui-btn-block" id="btnlogin" /></div><div style="height: 50px; text-align: center; line-height: 50px;"><span id="btnreg">注册账号</span>|<span id="">忘记密码</span></div></form></div><script src="js/mui.min.js"></script><script type="text/javascript">mui.init();document.getElementById("btnreg").addEventListener("tap",function(){console.log(11);mui.openWindow({url:"reg.html",id:"reg.html"});});document.getElementById("btnlogin").addEventListener("tap",function(){var vusername=document.getElementById("tbnusername").value;var vpassword=document.getElementById("tbnpassword").value; var requrl="http://192.168.43.242:8080/SweetyManage/JavaApi";localStorage.setItem("requrl",requrl);mui.ajax(requrl,{data:{rnum:"2",username:vusername,password:vpassword},dataType:'json',//服务器返回json格式数据type:'post',//HTTP请求类型timeout:10000,//超时时间设置为10秒;headers:{'Content-Type':'application/x-www-form-urlencoded'},success:function(data){console.log(JSON.stringify(data));if(data==null||data==""){mui.toast("用户名或者密码错误!");}else{console.log(data[0]);mui.toast("登录成功!");localStorage.setItem("id",data[0].id);localStorage.setItem("truename",data[0].truename);localStorage.setItem("tel",data[0].tel);localStorage.setItem("address",data[0].address);//登录成功之后就把当前人的信息保存在localStorage中mui.openWindow({url:"main.html",id:"main.html"});} }});});</script></body></html>
在car.html中加入id=“gotopay”
在car.html绑定好id
这个表示:用户将东西放到表单里面,我们再根据这个id区获取用户填写 的内容
car.html
(dg回车)通过localStorage拿到值显示到页面里面
这样收货人、电话号码、地址就可以显示出来了
四、确认下单
在car.html中设置id=gotoorder
car.html
下面这些代码的意思是
根据下单 在前端获取四个数据
发送到后端
至于这个rnum为多少去后端代码看JavaApi
首先看名字(这就是起名字需要特别注意的原因,要取一个别人能看得懂的命名,你的想法是多种多样的,说不定哪天你就改变主意了,自己都不知道你自己写的什么,除非你把注释打好哈哈哈一条一条地打),点中对的眼神,直接Go To ——》Declaration or Usages 就可以去看详细的接口啦!
car.html完整的代码
<!doctype html>
<html><head><meta charset="UTF-8"><title></title><meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /><link href="css/mui.min.css" rel="stylesheet" /><style type="text/css">#listbox{background-color: #fff;}#listbox ul{list-style: none;}#listbox ul li{height: 80px;border-bottom: solid 1px #eee;position: relative;}#listbox ul li img.propic{width:70px;height:70px;float: left;}#listbox ul li span{display: block;border: solid 1px #eee;width:28px;height:28px;text-align: center;line-height:28px;float: left;}.btnbox{width: 90px;height: 30px;position: absolute;right: 5px;top:20px;}.hidden{display: none;}.show{display: block;}</style></head><body><div class="mui-content"><div id="listbox"><ul id="itembox"><!--<li><img src="img/gou.png" class="propic"/><p style="padding-top: 15px;">华为5G手机</p><p>¥5888.00</p><div class="btnbox"><span>-</span><span>1</span><span>+</span></div></li>--></ul><p style="padding-left: 50px;padding-bottom: 20px;">总价:<span id="pricebox"></span></p></div><button type="button" class="mui-btn mui-btn-blue mui-btn-block" id="gotoprolist">继续购物</button><button type="button" class="mui-btn mui-btn-blue mui-btn-block" id="gotopay">去结算</button><div id="userinfobox" class="hidden"><form class="mui-input-group"><div class="mui-input-row"><label>收货人</label><input type="text" id="tbtruename" class="mui-input-clear" placeholder="收货人"></div><div class="mui-input-row"><label>电话</label><input type="text" id="tbtel" class="mui-input-clear" placeholder="电话"></div><div class="mui-input-row"><label>地址</label><input type="text" id="tbaddress" class="mui-input-clear" placeholder="地址"></div></form><button type="button" id="gotoorder" class="mui-btn mui-btn-blue mui-btn-block">确认下单</button></div></div><script src="js/mui.min.js"></script><script type="text/javascript">mui.init();mui.ready(function(){cardatainit();});document.getElementById("gotoorder").addEventListener("tap",function(){var truename=document.getElementById("tbtruename").value;var tel=document.getElementById("tbtel").value;var address=document.getElementById("tbaddress").value;var userid=localStorage.getItem("id");var requrl=localStorage.getItem("requrl");mui.ajax(requrl,{data:{rnum:"9",userid:userid,tbname:truename,tbaddress:address,tbtel:tel},dataType:'json',//服务器返回json格式数据type:'post',//HTTP请求类型timeout:10000,//超时时间设置为10秒;headers:{'Content-Type':'application/x-www-form-urlencoded'},success:function(data){mui.toast("下单成功!");mui.openWindow({url:"myorderlist.html",id:"myorderlist.html"});}});});//初始化购物车里面的数据function cardatainit(){//查询当前登录app的用户在购物车中加入的商品。 把查询出来的数据绑定到ul中。//需要的参数:useridvar requrl=localStorage.getItem("requrl");var userid=localStorage.getItem("id");/*<li><img src="img/gou.png" class="propic"/><p style="padding-top: 15px;">华为5G手机</p><p>¥5888.00</p><div class="btnbox"><span>-</span><span>1</span><span>+</span></div></li>*/mui.ajax(requrl,{data:{rnum:"6",userid:userid },dataType:'json',//服务器返回json格式数据type:'post',//HTTP请求类型timeout:10000,//超时时间设置为10秒;headers:{'Content-Type':'application/x-www-form-urlencoded'},success:function(data){console.log(JSON.stringify(data));var htmlstr="";var sumprice=0;for (var i=0;i<data.length;i++) {htmlstr+='<li>';htmlstr+='<img src="http://192.168.43.242:8080/SweetyManage/upload/'+data[i].imgurl+'" class="propic"/>';htmlstr+='<p style="padding-top: 15px;">'+data[i].proname+'</p>';htmlstr+='<p>¥'+data[i].price+'.00</p>';htmlstr+='<div class="btnbox" id="'+data[i].proid+'"><span class="btnjian">-</span><span class="numberbox">'+data[i].procount+'</span><span class="btnjia">+</span></div>';htmlstr+="</li>";sumprice +=parseInt(data[i].price)*parseInt(data[i].procount);// 单价*数量=小计 然后通过累加 把所有商品的价格累加起来 保存在sumprice中。 这里要注意,计算价格之前,要把单价和数量都转为数字。}document.getElementById("pricebox").innerText=sumprice;document.getElementById("itembox").innerHTML=htmlstr;}}); }//通过委托的方式给增加按钮绑定点击事件mui("#itembox").on("tap","span.btnjia",function(){var proid=this.parentNode.getAttribute("id");var userid=localStorage.getItem("id");var v=this.parentNode.querySelector(".numberbox").innerText;//获取该商品原来在购物车中的数量v=parseInt(v);v=v+1;var requrl=localStorage.getItem("requrl");mui.ajax(requrl,{data:{rnum:"8",userid:userid,id:proid,countvalue:v},dataType:'json',//服务器返回json格式数据type:'post',//HTTP请求类型timeout:10000,//超时时间设置为10秒;headers:{'Content-Type':'application/x-www-form-urlencoded'},success:function(data){cardatainit();}}); });mui("#itembox").on("tap","span.btnjian",function(){var proid=this.parentNode.getAttribute("id");var userid=localStorage.getItem("id");var v=this.parentNode.querySelector(".numberbox").innerText;//获取该商品原来在购物车中的数量v=parseInt(v);v=v-1;var requrl=localStorage.getItem("requrl");if(v<1){//如果购物车里面商品的数量小于1,就需要删除该商品mui.ajax(requrl,{data:{rnum:"7",userid:userid,id:proid},dataType:'json',//服务器返回json格式数据type:'post',//HTTP请求类型timeout:10000,//超时时间设置为10秒;headers:{'Content-Type':'application/x-www-form-urlencoded'},success:function(data){if(data.msg=="ok"){mui.toast("删除成功!");}cardatainit();}}); }else{//如果商品的数量不小于1,只需要将该商品的数量减少1就可以了。mui.ajax(requrl,{data:{rnum:"8",userid:userid,id:proid,countvalue:v},dataType:'json',//服务器返回json格式数据type:'post',//HTTP请求类型timeout:10000,//超时时间设置为10秒;headers:{'Content-Type':'application/x-www-form-urlencoded'},success:function(data){cardatainit();}}); }});//点击去结算按钮document.getElementById("gotopay").addEventListener("tap",function(){document.getElementById("tbtruename").value=localStorage.getItem('truename');document.getElementById("tbtel").value=localStorage.getItem('tel');document.getElementById("tbaddress").value=localStorage.getItem('address');document.getElementById("userinfobox").className="show";});//点击继续购物按钮document.getElementById("gotoprolist").addEventListener("tap",function(){var main=plus.webview.getWebviewById("main.html");mui.fire(main,'goprolist'); });//自定义事件,用于在其他页面触发 刷新购物车里面商品列表数据document.addEventListener('initdata', function() {cardatainit();});</script></body></html>
后端这边注释我写好啦
JavaApi.java(后端接口)后端代码关于下单这里的注释我写好了
package com.rz;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;/*** Servlet implementation class JavaApi*/
@WebServlet(name="JavaApi",value="/JavaApi")
public class JavaApi extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public JavaApi() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request,response);}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");String rnum=request.getParameter("rnum"); response.setCharacterEncoding("utf-8");response.setContentType("text/json;charset=utf-8"); response.setHeader("Access-Control-Allow-Origin","*");response.setHeader("Access-Control-Allow-Methods","PUT, GET, POST, DELETE, OPTIONS");response.setHeader("Access-Control-Allow-Headers","X-Requested-With");response.setHeader("Access-Control-Allow-Headers","Content-Type");System.out.print(rnum);if(rnum!=null){switch(rnum){case "1":userreg(request,response);break;case "2":userlogin(request,response);break;case "3":getprolist(request,response);break;case "4":getprobyid(request,response);break;case "5":addtocar(request,response);break;case "6":getcarlist(request,response);break;case "7":deleteCarPro(request,response);break;case "8":updateCarCount(request,response);break;case "9":addToOrder(request,response);break;case "10":getorderlist(request,response);break;case "11":getOrderView(request,response);break;}}else {response.getWriter().write("{\"result\":\"nodata\"}");}}//用户注册protected void userreg(HttpServletRequest request, HttpServletResponse response) throws IOException{String username=request.getParameter("username");String password=request.getParameter("password");String truename=request.getParameter("truename");String tel=request.getParameter("tel");String address=request.getParameter("address");String StrSql1="insert into tbmember (username,password,truename,tel,address) values (?,?,?,?,?)";List<Object> params1 = new ArrayList<Object>();params1.add(username);params1.add(password);params1.add(truename);params1.add(tel);params1.add(address);DBHelper Dal=new DBHelper();Dal.excuteSql(StrSql1, params1);response.setCharacterEncoding("utf-8");response.setContentType("text/json;charset=utf-8");response.getWriter().write("{\"msg\":\"ok\"}");}//用户登录protected void userlogin(HttpServletRequest request, HttpServletResponse response) throws IOException{String username=request.getParameter("username");String password=request.getParameter("password");DBHelper Dal=new DBHelper();String strSql=" select * from tbmember where username=? and password=? ";List<Object> params = new ArrayList<Object>();params.add(username);params.add(password);List<Map<String, Object>> userlist = null;try {userlist=Dal.executeQuery(strSql, params);} catch (SQLException e) {e.printStackTrace();}String jsonstr =JSON.toJSONString(userlist);response.setCharacterEncoding("utf-8");response.setContentType("text/json;charset=utf-8");response.getWriter().write(jsonstr);}//获取商品列表protected void getprolist(HttpServletRequest request, HttpServletResponse response) throws IOException{DBHelper Dal=new DBHelper();String strSqlpager=" select * from tbproduct order by id desc";List<Map<String, Object>> listpage = null;try {List<Object> params = new ArrayList<Object>();listpage=Dal.executeQuery(strSqlpager, params);String jsonstr =JSON.toJSONString(listpage);response.getWriter().write(jsonstr);} catch (SQLException e) {e.printStackTrace();}}//根据商品id获取商品明细protected void getprobyid(HttpServletRequest request, HttpServletResponse response) throws IOException{DBHelper Dal=new DBHelper();String id=request.getParameter("id");String strSqlpager=" select * from tbproduct where id=? ";Map<String, Object> objectbyid = null;List<Object> params = new ArrayList<Object>();params.add(id);objectbyid=Dal.getSingleObject(strSqlpager, params);String jsonstr =JSON.toJSONString(objectbyid);response.getWriter().write(jsonstr);}//获取首页商品列表protected void getindexproindexlist(HttpServletRequest request, HttpServletResponse response) throws IOException{DBHelper Dal=new DBHelper();String strSqlpager=" select * from tbproduct order by id desc limit 0,4";List<Map<String, Object>> listpage = null;try {List<Object> params = new ArrayList<Object>();listpage=Dal.executeQuery(strSqlpager, params);String jsonstr =JSON.toJSONString(listpage);response.getWriter().write(jsonstr);} catch (SQLException e) {e.printStackTrace();}}//加入购物车protected void addtocar(HttpServletRequest request, HttpServletResponse response) throws IOException{String proid=request.getParameter("proid");String userid=request.getParameter("userid");DBHelper db=new DBHelper();Boolean flag=false;String StrSqlexist="select * from tbshoppingcar where userid=? and proid=? ";List<Map<String, Object>> carrecordlist = null;List<Object> paramsexist = new ArrayList<Object>();paramsexist.add(userid);paramsexist.add(proid);try {carrecordlist=db.executeQuery(StrSqlexist, paramsexist);} catch (SQLException e) {e.printStackTrace();}if(carrecordlist.size()>0){flag=true;}if(flag){//修改个数String strSql1="update tbshoppingcar set procount=procount+1 where userid=? and proid=? ";List<Object> paramsupdate = new ArrayList<Object>();paramsupdate.add(userid);paramsupdate.add(proid);db.excuteSql(strSql1, paramsupdate);}else{//根据id把商品信息查询出来。List<Object> params = new ArrayList<Object>();String StrSqlpro="select * from tbproduct where id="+proid;Map<String, Object> obj=db.getSingleObject(StrSqlpro, params);SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式String createtime=df.format(new Date());//新增String strSql2="insert into tbshoppingcar (userid,proname,proid,procount,ctime,imgurl,price) values(?,?,?,?,?,?,?) ";params.add(userid);params.add(obj.get("proname"));params.add(proid);params.add(1);params.add(createtime);params.add(obj.get("imgurl"));params.add(obj.get("price"));db.excuteSql(strSql2, params);}response.setCharacterEncoding("utf-8");response.setContentType("text/json;charset=utf-8");response.getWriter().write("{\"msg\":\"ok\"}");}//获取购物车商品列表protected void getcarlist(HttpServletRequest request, HttpServletResponse response) throws IOException{String userid=request.getParameter("userid");List<Map<String, Object>> carlistall = null;List<Object> params2 = new ArrayList<Object>();DBHelper Dal=new DBHelper();String strSqlpager=" select * from tbshoppingcar where userid=? ";params2.add(userid);try {carlistall=Dal.executeQuery(strSqlpager, params2);String jsonstr =JSON.toJSONString(carlistall);response.getWriter().write(jsonstr);} catch (SQLException e) {e.printStackTrace();}}//删除购物车商品protected void deleteCarPro(HttpServletRequest request, HttpServletResponse response) throws IOException{String id=request.getParameter("id");String userid=request.getParameter("userid");String strSql="delete from tbshoppingcar where userid=? and proid=? ";DBHelper db=new DBHelper();List<Object> params = new ArrayList<Object>();params.add(userid);params.add(id);db.excuteSql(strSql, params);response.setCharacterEncoding("utf-8");response.setContentType("text/json;charset=utf-8");response.getWriter().write("{\"msg\":\"ok\"}");}//修改购物车数量protected void updateCarCount(HttpServletRequest request, HttpServletResponse response) throws IOException{String id=request.getParameter("id");String countvalue=request.getParameter("countvalue");String userid=request.getParameter("userid");String strSql="update tbshoppingcar set procount=? where userid=? and proid=? ";DBHelper db=new DBHelper();List<Object> params = new ArrayList<Object>();params.add(countvalue);params.add(userid);params.add(id);db.excuteSql(strSql, params);response.setCharacterEncoding("utf-8");response.setContentType("text/json;charset=utf-8");response.getWriter().write("{\"msg\":\"ok\"}");}//下单接口protected void addToOrder(HttpServletRequest request, HttpServletResponse response) throws IOException{//从移动端接受参数Map<String, Object> obj=(Map<String,Object>)request.getSession().getAttribute("currentuser");String tbname=request.getParameter("tbname");String tbtel=request.getParameter("tbtel");String tbaddress=request.getParameter("tbaddress");String userid=request.getParameter("userid");//查询当前这个人购物车里面添加的商品String strSqlcarpros="select * from tbshoppingcar where userid=? ";//定义参数对象DBHelper db=new DBHelper();//定义一个容器用于保存查询的结果List<Object> params = new ArrayList<Object>();params.add(userid);List<Map<String,Object>> carprolist=null;try {carprolist=db.executeQuery(strSqlcarpros,params);} catch (SQLException e) {e.printStackTrace();}//If:判断当前这个人是否在购物车中是否加入了商品,如果没有直接返回什么都不做if(!(carprolist.size()>0)){return;}//准备根据当前系统的时间生成一个订单号//New一个时间对象出来,主要用于获取系统当前的时间Date t=new Date();//接下来定义两种显示时间的格式SimpleDateFormat df1 = new SimpleDateFormat("yyyyMMddHHmmssSSS");SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//使用这两种格式来格式化系统当前的时间String orderid=df1.format(t);String createtime=df2.format(t);//定义了一个sum变量,这个变量用于计算订单的总价格int sum=0;//通过for循环遍历当前用户添加的商品,每次循环就向订单明细表中插入一条数据for (Map<String, Object> m : carprolist) {//累加每个商品的小计 小计=单价*数量。把每个商品的小计累加起来,就得到了所有商品的总计,也就是该订单的总价//Sum=单价*数量=当前这个商品的汇总sum=sum+Integer.parseInt(m.get("price").toString())*Integer.parseInt(m.get("procount").toString());//从购物车当中取出来的商品明细插入到订单明细表中String strSqlitems="insert into tborderitems (orderid,proid,proname,price,procount,imgurl) values (?,?,?,?,?,?)";List<Object> paramsitems = new ArrayList<Object>();paramsitems.add(orderid);paramsitems.add(m.get("proid"));paramsitems.add(m.get("proname"));paramsitems.add(m.get("price"));paramsitems.add(m.get("procount"));paramsitems.add(m.get("imgurl"));db.excuteSql(strSqlitems, paramsitems);}//向订单抬头表插入订单的收货人信息String StrSql1="insert into tborderhead (orderid,sname,stel,saddress,sumprice,memberid,ctime) values (?,?,?,?,?,?,?)";List<Object> params1 = new ArrayList<Object>();params1.add(orderid);params1.add(tbname);params1.add(tbtel);params1.add(tbaddress);params1.add(sum);params1.add(userid);params1.add(createtime);db.excuteSql(StrSql1, params1);//下单完成后清空购物车。把当前这个人在购物车加入的商品删除掉String strSqlClearCar="delete from tbshoppingcar where sessionid=?";db.excuteSql(strSqlClearCar, params);//告诉移动端下单操作完成response.setCharacterEncoding("utf-8");response.setContentType("text/json;charset=utf-8");response.getWriter().write("{\"msg\":\"ok\"}");}//获取订单列表protected void getorderlist(HttpServletRequest request, HttpServletResponse response) throws IOException{DBHelper Dal=new DBHelper();String currentid=request.getParameter("currentid");String strSqlpager=" select * from v_order where memberid=? order by id desc";List<Map<String, Object>> listpage = null;try {List<Object> params = new ArrayList<Object>();params.add(currentid);listpage=Dal.executeQuery(strSqlpager, params);String jsonstr =JSON.toJSONString(listpage);response.getWriter().write(jsonstr);} catch (SQLException e) {e.printStackTrace();}}//获取订单明细protected void getOrderView(HttpServletRequest request, HttpServletResponse response) throws IOException{String orderid=request.getParameter("orderid");DBHelper Dal=new DBHelper();String strSql1=" select * from tborderhead where orderid=? ";Map<String, Object> objbyid = null;List<Object> params = new ArrayList<Object>();params.add(orderid);objbyid=Dal.getSingleObject(strSql1, params);String strSql2=" select * from tborderitems where orderid=? ";List<Map<String,Object>> listitems=new ArrayList<Map<String, Object>>();try {listitems=Dal.executeQuery(strSql2, params);} catch (SQLException e) {e.printStackTrace();}Map<String, Object> map = new HashMap<String, Object>();map.put("orderhead", objbyid);map.put("orderitems", listitems);String jsonstr =JSON.toJSONString(map);response.getWriter().write(jsonstr);}//获取新闻列表protected void getNewsList(HttpServletRequest request, HttpServletResponse response) throws IOException{int currentpage=1;int pagesize=10;try{String p=request.getParameter("p");currentpage = Integer.valueOf(p);}catch(Exception e){currentpage=1;}DBHelper Dal=new DBHelper();//查询全部String strSql=" select id from tbnews order by id desc ";List<Map<String, Object>> listall = null;List<Object> params = new ArrayList<Object>();try {listall=Dal.executeQuery(strSql, params);} catch (SQLException e) {e.printStackTrace();}//分页查询int startindex=pagesize*(currentpage-1);String strSqlpager=" select * from tbnews order by id desc limit "+startindex+","+pagesize+"";List<Map<String, Object>> listpage = null;try {listpage=Dal.executeQuery(strSqlpager, params);String jsonstr =JSON.toJSONString(listpage);response.getWriter().write(jsonstr);} catch (SQLException e) {e.printStackTrace();}}}
五、显示我的订单
这里要分清一件事就是有两个表
-
抬头表(后面有多的两个字段是用来做备注时间与备注的)
收货人 和 总价
在数据库当中是这样子的
-
订单明细表
订单号订单名价格和数量
在数据库当中是这样子的
接下来要实现的功能是:点击确定下单就会进入我的订单
实现我的订单页面的跳转
新建一个myorderlist.html(mui框架)
myorderlist.html
<!doctype html>
<html><head><meta charset="UTF-8"><title></title><meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /><link href="css/mui.min.css" rel="stylesheet" /></head><body><header class="mui-bar mui-bar-nav"><a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a><h1 class="mui-title">我的订单</h1></header><div class="mui-content"><div class="mui-scroll-wrapper"><div class="mui-scroll"><div style="height: 50px;"></div><div id="orderlistbox"></div> </div></div></div><script src="js/mui.min.js"></script><script type="text/javascript">mui.init();mui('.mui-scroll-wrapper').scroll({indicators: false, //是否显示滚动条deceleration:0.00006, //阻尼系数,系数越小滑动越灵敏bounce: true //是否启用回弹});/*<div class="mui-card"><div class="mui-card-header mui-card-media"><img src="img/gou.png" /><div class="mui-media-body">订单号:202011251101021<p>下单时间: 2016-06-30 15:30</p></div></div><div class="mui-card-content" ><div style="margin: 10px;"><p>收货人:张三</p><p>电话:15366665555</p><p>地址:重庆市巴南区</p> </div></div><div class="mui-card-footer"><a class="mui-card-link">总价:¥5000.00</a><a class="mui-card-link">查看明细</a></div></div> */mui.ready(function(){var requrl=localStorage.getItem("requrl");var currentuserid=localStorage.getItem("id");console.log(currentuserid);mui.ajax(requrl,{data:{rnum:"10",currentid:currentuserid, },dataType:'json',//服务器返回json格式数据type:'post',//HTTP请求类型timeout:10000,//超时时间设置为10秒;headers:{'Content-Type':'application/x-www-form-urlencoded'},success:function(data){console.log(JSON.stringify(data));var orderhtml="";for (var i=0;i<data.length;i++) {orderhtml+='<div class="mui-card" id="'+data[i].orderid+'">';orderhtml+='<div class="mui-card-header mui-card-media">';orderhtml+='<img src="imgs/sweety.png" />';orderhtml+='<div class="mui-media-body">';orderhtml+='订单号:'+data[i].orderid;orderhtml+='<p>下单时间:'+data[i].ctime+'</p>';orderhtml+='</div>';orderhtml+='</div>';orderhtml+='<div class="mui-card-content" >';orderhtml+='<div style="margin: 10px;">';orderhtml+='<p>收货人:'+data[i].sname+'</p>';orderhtml+='<p>电话:'+data[i].stel+'</p>';orderhtml+='<p>地址:'+data[i].saddress+'</p> ';orderhtml+='</div>';orderhtml+='</div>';orderhtml+='<div class="mui-card-footer">';orderhtml+='<a class="mui-card-link">总价:¥'+data[i].sumprice+'.00</a>';orderhtml+='<a class="mui-card-link">查看明细</a>';orderhtml+='</div>';orderhtml+='</div> ';}document.getElementById("orderlistbox").innerHTML=orderhtml;}});});mui("#orderlistbox").on("tap","div.mui-card",function(){var orderid=this.getAttribute("id");mui.openWindow({url:"myorderview.html",id:"myorderview.html",extras:{orderid:orderid}});});</script></body></html>
myorderview.html
<!doctype html>
<html><head><meta charset="UTF-8"><title></title><meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /><link href="css/mui.min.css" rel="stylesheet" />.<style type="text/css">p.title{height:26px;line-height: 35px;padding-left: 10px;}</style></head><body><header class="mui-bar mui-bar-nav"><a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a><h1 class="mui-title">订单明细</h1></header><div class="mui-content" style="padding-top: 30px;"><p class="title">收货人信息</p><ul class="mui-table-view"><li class="mui-table-view-cell">订单号:<span id="tborderid"></span></li><li class="mui-table-view-cell">下单时间:<span id="tbctime"></span></li><li class="mui-table-view-cell">收货人:<span id="tbtruename"></span></li><li class="mui-table-view-cell">电话:<span id="tbtel"></span></li><li class="mui-table-view-cell">地址:<span id="tbaddress"></span></li><li class="mui-table-view-cell">总价:¥<span id="tbsumprice"></span></li></ul><p class="title">购买的商品</p><ul class="mui-table-view" id="itemsbox"></ul></div><script src="js/mui.min.js"></script><script type="text/javascript">mui.init();mui.plusReady(function(){var self = plus.webview.currentWebview();var orderid=self.orderid;console.log(orderid);var requrl=localStorage.getItem("requrl");mui.ajax(requrl,{data:{rnum:"11",orderid:orderid},dataType:'json',//服务器返回json格式数据type:'post',//HTTP请求类型timeout:10000,//超时时间设置为10秒;headers:{'Content-Type':'application/x-www-form-urlencoded'},success:function(data){//console.log(JSON.stringify(data));console.log(JSON.stringify(data.orderitems))document.getElementById("tborderid").innerText=data.orderhead.orderid;document.getElementById("tbctime").innerText=data.orderhead.ctime;document.getElementById("tbtruename").innerText=data.orderhead.sname;document.getElementById("tbtel").innerText=data.orderhead.stel;document.getElementById("tbaddress").innerText=data.orderhead.saddress;document.getElementById("tbsumprice").innerText=data.orderhead.sumprice;/*<li class="mui-table-view-cell mui-media"><a href="javascript:;"><img class="mui-media-object mui-pull-left" src="http://placehold.it/40x30"><div class="mui-media-body">华为P40 5G手机<p class="mui-ellipsis">1555.00x1</p></div></a></li> */var itemshtml="";for (var i=0;i<data.orderitems.length;i++) {itemshtml+='<li class="mui-table-view-cell mui-media">';itemshtml+='<a href="javascript:;">';itemshtml+='<img class="mui-media-object mui-pull-left" src="http://192.168.43.242:8080/SweetyManage/upload/'+data.orderitems[i].imgurl+'">';itemshtml+='<div class="mui-media-body">';itemshtml+=data.orderitems[i].proname;itemshtml+='<p class="mui-ellipsis">'+data.orderitems[i].price+'.00x'+data.orderitems[i].procount+'</p>';itemshtml+=' </div>';itemshtml+='</a>';itemshtml+='</li> ';}document.getElementById("itemsbox").innerHTML=itemshtml;}});});</script></body></html>
最后肯定要绑定点击事件啊(想都不用想哈哈哈哈)
在my.html中添加我的订单的id为btngotoorderlist
再加入dg(回车),绑定点击事件, 然后点击 我的—》我的订单 就跳转到我的订单的详细页面
演示
在我的后台管理系统已经收到数据
六、退出系统
给退出系统设置id=“btnlogout”
my.html
添加点击事件
my.html
my.html
<!doctype html>
<html><head><meta charset="UTF-8"><title></title><meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /><link href="css/mui.min.css" rel="stylesheet" /></head><body><div class="mui-content"><ul class="mui-table-view"><li id="btngotoorderlist" class="mui-table-view-cell"><a class="mui-navigate-right">我的订单</a></li><li class="mui-table-view-cell"><a class="mui-navigate-right">修改密码</a></li><li class="mui-table-view-cell"><a class="mui-navigate-right">反馈意见</a></li><li class="mui-table-view-cell" id='btnaboutUs'><a class="mui-navigate-right">关于我们</a></li><li class="mui-table-view-cell" id="btnlogout"><a class="mui-navigate-right">退出系统</a></li></ul></div><script src="js/mui.min.js"></script><script type="text/javascript">mui.init()document.getElementById("btnaboutUs").addEventListener("tap",function(){var webview = mui.openWindow({url:'aboutUs.html',extras:{name:'wangtiantian' , //扩展参数time:'2020-11-4'}});
// console.log("123") 用来调试代码})document.getElementById("btngotoorderlist").addEventListener("tap",function(){mui.openWindow({url:"myorderlist.html",id:"myorderlist.html"});}); document.getElementById("btnlogout").addEventListener("tap",function(){localStorage.removeItem("id");localStorage.removeItem("truename");localStorage.removeItem("address");localStorage.removeItem("tel");mui.openWindow({url:"login.html",id:"login.html"});});</script></body></html>
这个很简单就不用演示了哈哈哈哈
哇塞你已经看到这里来了,简直不是一般人哈哈哈!
这里说一个报错哈哈哈(大部分人都会有这个情况,昨天我运行后端程序,报了这个错)想了半天没想出来,结果是数据库服务没开,哈哈哈哈哈哈,这种低级错误。
https://blog.csdn.net/hanhanwanghaha欢迎关注这个超级无敌可爱的人鸭,有什么问题留言私信皆可,看见必回!
创作不易,如有转载,请注明出处
希望你我可以一直走在梦想的路上,即使身在低谷,也不忘前行