首先我们先解决一下上次购物车的乱码问题
分析乱码问题:
1.前台—->浏览器那一端就已经产生了乱码(已分析,排除)
2.后端—->在子控制器接受前端传递到后台的过程中出现了乱码
由图可知,点击F12,进入控制台,在右下角我们可以看到书名《时光走了你还在》,并没有乱码,所以我们分析的第一个疑点就可以排除了。
确定原因:就是前端正常的字符串传递到后台,出现了乱码,意味着中间做了编码的转换
(编码解码)
解决:
找到文件过滤器
EncodingFiter源码
package com.zking.util;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 娑擃厽鏋冩稊杈╃垳婢跺嫮鎮?
*
*/
@WebFilter("*.action")
public class EncodingFiter implements Filter {
private String encoding = "UTF-8";// 姒涙顓荤?涙顑侀梿锟?
public EncodingFiter() {
super();
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
// 娑擃厽鏋冩径鍕倞韫囧懘銆忛弨鎯у煂 chain.doFilter(request, response)閺傝纭堕崜宥夋桨
res.setContentType("text/html;charset=" + this.encoding);
if (req.getMethod().equalsIgnoreCase("post")) {
req.setCharacterEncoding(this.encoding);
}
// else {
// Map map = req.getParameterMap();// 娣囨繂鐡ㄩ幍锟介張澶婂棘閺佹澘鎮?=閸欏倹鏆熼崐锟?(閺佹壆绮?)閻ㄥ嚜ap闂嗗棗鎮?
// Set set = map.keySet();// 閸欐牕鍤幍锟介張澶婂棘閺佹澘鎮?
// Iterator it = set.iterator();
// while (it.hasNext()) {
// String name = (String) it.next();
// String[] values = (String[]) map.get(name);// 閸欐牕鍤崣鍌涙殶閸婄畅濞夘煉绱伴崣鍌涙殶閸婇棿璐熸稉锟芥稉顏呮殶缂佸垟
// for (int i = 0; i < values.length; i++) {
// values[i] = new String(values[i].getBytes("ISO-8859-1"),
// this.encoding);
// }
// }
// }
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
String s = filterConfig.getInitParameter("encoding");// 鐠囪褰噖eb.xml閺傚洣娆㈡稉顓㈠帳缂冾喚娈戠?涙顑侀梿锟?
if (null != s && !s.trim().equals("")) {
this.encoding = s.trim();
}
}
}
因为我们的界面是UTF-8的编码格式,但是在过滤器里面是ISO-8859-1,所以我们注释这一段,重新运行
没有乱码了
一.购物车结算
①建立Order与Orderitem实体类
order
package com.lsy.entity;
import java.util.Date;
public class Order {
private long id;
private long uid;
private Date orderTime;
private String consignee;
private String phone;
private String postalcode;
private String address;
private int sendType;
private Date sendTime;
private float orderPrice;
private int orderState;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getUid() {
return uid;
}
public void setUid(long uid) {
this.uid = uid;
}
public Date getOrderTime() {
return orderTime;
}
public void setOrderTime(Date orderTime) {
this.orderTime = orderTime;
}
public String getConsignee() {
return consignee;
}
public void setConsignee(String consignee) {
this.consignee = consignee;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPostalcode() {
return postalcode;
}
public void setPostalcode(String postalcode) {
this.postalcode = postalcode;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getSendType() {
return sendType;
}
public void setSendType(int sendType) {
this.sendType = sendType;
}
public Date getSendTime() {
return sendTime;
}
public void setSendTime(Date sendTime) {
this.sendTime = sendTime;
}
public float getOrderPrice() {
return orderPrice;
}
public void setOrderPrice(float orderPrice) {
this.orderPrice = orderPrice;
}
public int getOrderState() {
return orderState;
}
public void setOrderState(int orderState) {
this.orderState = orderState;
}
@Override
public String toString() {
return "Order [id=" + id + ", uid=" + uid + ", orderTime=" + orderTime + ", consignee=" + consignee + ", phone="
+ phone + ", postalcode=" + postalcode + ", address=" + address + ", sendType=" + sendType
+ ", sendTime=" + sendTime + ", orderPrice=" + orderPrice + ", orderState=" + orderState + "]";
}
}
Orderitem
package com.lsy.entity;
public class OrderItem {
private long id;
private long oid;
private String bid;
private int quantity;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getOid() {
return oid;
}
public void setOid(long oid) {
this.oid = oid;
}
public String getBid() {
return bid;
}
public void setBid(String bid) {
this.bid = bid;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
@Override
public String toString() {
return "OrderItem [id=" + id + ", oid=" + oid + ", bid=" + bid + ", quantity=" + quantity + "]";
}
}
②OrderDao与OrderItemDao
OrderDao
package com.lsy.dao;
import java.util.List;
import com.lsy.entity.Order;
import com.zking.util.BaseDao;
import com.zking.util.PageBean;
public class OrderDao extends BaseDao<Order>{
/**
* 购物车结算生成订单
* @param t
* @throws Exception
*/
public void add(Order t) throws Exception {
String sql="insert into t_easyui_order(uid,orderTime,consignee,phone,postalcode,address,sendType,sendTime,orderPrice,orderState) values(?,now(),?,?,?,?,?,?,?,?)";
super.executeUpdate(sql, t, new String[] {"uid","consignee","phone","postalcode","address","sendType","sendTime","orderPrice","orderState"});
}
/**
* 按照订单时间倒序查询
* @param order
* @param pageBean
* @return
* @throws Exception
*/
public List<Order> list(Order order, PageBean pageBean) throws Exception {
String sql="select * from t_easyui_order order by orderTime desc";
return super.executeQuery(sql, Order.class, pageBean);
}
}
OrderItemDao
package com.lsy.dao;
import com.lsy.entity.OrderItem;
import com.zking.util.BaseDao;
public class OrderItemDao extends BaseDao<OrderItem>{
/**
* 购物车结算订单项入库
* @param t
* @throws Exception
*/
public void add(OrderItem t) throws Exception {
String sql="insert into t_easyui_orderItem(oid,bid,quantity) values(?,?,?)";
super.executeUpdate(sql, t, new String[] {"oid","bid","quantity"});
}
}
ShoppingAction
package com.lsy.web;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lsy.dao.BookDao;
import com.lsy.dao.OrderDao;
import com.lsy.dao.OrderItemDao;
import com.lsy.entity.Book;
import com.lsy.entity.Order;
import com.lsy.entity.OrderItem;
import com.lsy.entity.User;
import com.lsy.vo.ShoppingVo;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriver;
import com.zking.util.ResponseUtil;
import com.zking.util.StringUtils;
public class ShoppingAction extends ActionSupport implements ModelDriver<ShoppingVo>{
private ShoppingVo vo=new ShoppingVo();
private OrderDao orderDao=new OrderDao();
private OrderItemDao orderItemDao=new OrderItemDao();
private BookDao bookDao=new BookDao();
public ShoppingVo getModel() {
return vo;
}
public void createOrder(HttpServletRequest req, HttpServletResponse resp) {
/**
* 1.数据入订单表
* 2.数据入订单项表
* 3.下单结束后,要将商品的销售数量发生改变
*/
User cuser=(User)req.getSession().getAttribute("cuser");
if(cuser==null) {
return ;
}
//组装数据
Order order=new Order();
order.setAddress(vo.getAddress());
order.setConsignee(vo.getConsignee());
//订单价格总计
float orderPrice=0f;
String pageStr = vo.getPageStr();
if(StringUtils.isNotBlank(pageStr)&&pageStr.length()>1) {
for(String item:pageStr.substring(1).split(",")) {
String[] itemEle = item.split("-");
orderPrice+=Float.valueOf(itemEle[3]);
}
}
order.setOrderPrice(orderPrice);
order.setOrderState(1);
order.setPhone(vo.getPhone());
order.setPostalcode(vo.getPostalcode());
order.setSendType(vo.getSendType());
order.setUid(cuser.getId());
try {
orderDao.add(order);
Order newest = orderDao.list(null, null).get(0);
OrderItem oi=new OrderItem();
if(StringUtils.isNotBlank(pageStr)&&pageStr.length()>1) {
for(String item:pageStr.substring(1).split(",")) {
String[] itemEle = item.split("-");
oi.setBid(itemEle[0]);
//需要设置当前订单项是属于哪个订单的,思路是查询出最新订单的id
//按照订单事件进行倒序查询,取第一条数据即可
oi.setOid(newest.getId());
oi.setQuantity(Integer.valueOf(2));
orderItemDao.add(oi);
//当前书籍被购买,那么这本书销量应该+Quantity
Book b=new Book();
b.setName(itemEle[0]);
b.setSales(Integer.valueOf(itemEle[2]));
bookDao.editSales(b);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 将信息加入购物车
*/
public String add(HttpServletRequest req, HttpServletResponse resp) {
HttpSession session = req.getSession();
User cuser = (User)session.getAttribute("cuser");
ObjectMapper om=new ObjectMapper();
try {
if(cuser!=null) {
/**
* 点击添加传递到后台的是一个对象,然后购物车需要的是list集合进行显示
* 1.第一次添加购物车中是没有数据的,也就意味着把vo放到list集合shopGoodsVos中,传递到前台即可
* 2.第二次添加到购物车 也就意味着之前有购物车相关信息
* 取出原有的购物车list集合,将本次添加购物车的实体类Vo放到原有的购物车list集合shopGoodsVos中
*/
long uid = cuser.getId();
List<ShoppingVo> shopGoodsVos=null;
//从session取出当前用户对应的购物车信息
String shoppingInfo = (String)session.getAttribute("shopping_"+uid);
if(StringUtils.isNotBlank(shoppingInfo)) {
//第2/3次添加
//shoppingInfo包含了当前用户的购物车信息,也是通过list集合转成的一个Json字符串
shopGoodsVos = om.readValue(shoppingInfo, List.class);
}else {
//第1次添加
shopGoodsVos =new ArrayList<ShoppingVo>();
}
//vo指的是前台点击购物车具体商品内容
shopGoodsVos.add(vo);
session.setAttribute("shopping_"+uid, om.writeValueAsString(shopGoodsVos));
// session.setAttribute("shopping_"+uid, vo);
req.setAttribute("shopGoodsVos", shopGoodsVos);
// req.setAttribute("shoppingCar", arg1);
}
} catch (Exception e) {
e.printStackTrace();
}
return "shoppingCar";
}
public String list(HttpServletRequest req, HttpServletResponse resp) {
HttpSession session = req.getSession();
User cuser = (User)session.getAttribute("cuser");
ObjectMapper om=new ObjectMapper();
//查询当前用户的购物车信息
String shoppingInfo = (String)session.getAttribute("shopping_"+cuser.getId());
try {
List<ShoppingVo> shopGoodsVos=om.readValue(shoppingInfo, List.class);
req.setAttribute("shopGoodsVos", shopGoodsVos);
} catch (Exception e) {
e.printStackTrace();
}
return "shoppingCar";
}
public void clear(HttpServletRequest req, HttpServletResponse resp) {
HttpSession session = req.getSession();
User cuser = (User)session.getAttribute("cuser");
session.removeAttribute("shopping_"+cuser.getId());
try {
ResponseUtil.write(resp, 1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
前台js代码
$(".order_Create").click(function () {
var consignee = $("#consignee").val();
var phone = $("#phone").val();
var postalcode = $("#postalcode").val();
var address = $("#address").val();
var sendType = $("#sendType").val();
var single_tr = "";
$(".table tr:gt(0)").not(":last").each(function (index, node) {
console.log(index);
single_tr = single_tr + "," + $(this).find("th").eq(0).html() + "-" + $(this).find("td").eq(0).html() + "-"
+ $(this).find("td").eq(1).find("input").val() + "-" + $(this).find("td").eq(2).html();
})
console.log(single_tr.substring(1));
var param = "consignee=" + consignee + "&phone=" + phone + "&postalcode=" + postalcode + "&address=" + address + "&sendType=" + sendType + "&pageStr=" + single_tr;
$.ajax({
url: '${pageContext.request.contextPath}/shopping.action?methodName=createOrder',
type: "POST",
data: param,
success: function (data) {
var consignee = $("#consignee").val("");
var phone = $("#phone").val("");
var postalcode = $("#postalcode").val("");
var address = $("#address").val("");
var sendType = $("#sendType").val("");
$('.shop-modal').addClass('modal');
$(".table tr:gt(0)").not(":last").remove();
$.ajax({
url: '${pageContext.request.contextPath}/shopping.action?methodName=clear',
success: function (data) {
<%--location.href = '${pageContext.request.contextPath}/shopping.action?methodName=list';--%>
}
});
}
});
});
界面展示
bye~
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/12236.html