企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## 步骤 1 : 先运行,看到效果,再学习 先将完整的 tmall_ssm 项目(向老师要相关资料),配置运行起来,确认可用之后,再学习做了哪些步骤以达到这样的效果。 ## 步骤 2 : 模仿和排错 在确保可运行项目能够正确无误地运行之后,再严格照着教程的步骤,对代码模仿一遍。 模仿过程难免代码有出入,导致无法得到期望的运行结果,此时此刻通过比较**正确答案** ( 可运行项目 ) 和自己的代码,来定位问题所在。 采用这种方式,**学习有效果,排错有效率**,可以较为明显地提升学习速度,跨过学习路上的各个槛。 ## 步骤 3 : 结算页操作 首先通过立即购买或者购物车的提交到结算页面 进入结算页面,然后点击提交订单 ![](https://box.kancloud.cn/29fe10b64c21a31c40bf077949cad9dc_217x74.png) ## 步骤 4 : 运行效果 提交订单后,在数据库中生成一条Order记录。 不仅如此,订单项的oid字段也会被设置为这条Order记录的id ![](https://box.kancloud.cn/5cfb72349b8fbd0b523803f1f11f845f_1469x55.png) ## 步骤 5 : applicationContext.xml 在最后增加事务管理配置: ~~~ <!--事务管理 --> <tx:annotation-driven transaction-manager="transactionManager" /> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> ~~~ 因为增加订单行为需要同时修改两个表 1. 为Order表新增数据 2. 修改OrderItem表 所以需要进行事务管理,否则当新增了Order表的数据,还没有来得及修改OrderItem的时候出问题,比如突然断电,那么OrderItem的数据就会是脏数据了(没有指向正确的Order表数据)。 ~~~ <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <context:annotation-config /> <context:component-scan base-package="com.dodoke.tmall.service" /> <!-- 导入数据库配置文件 --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 配置数据库连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 基本属性 url、user、password --> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="1" /> <property name="minIdle" value="1" /> <property name="maxActive" value="20" /> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="60000" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000" /> <property name="validationQuery" value="SELECT 1" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <!-- 打开PSCache,并且指定每个连接上PSCache的大小 --> <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> </bean> <!--Mybatis的SessionFactory配置 --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="typeAliasesPackage" value="com.dodoke.tmall.pojo" /> <property name="dataSource" ref="dataSource" /> <property name="mapperLocations" value="classpath:mapper/*.xml" /> <!--分页插件,目前先注释,后面重构的时候才会使用 --> <property name="plugins"> <array> <bean class="com.github.pagehelper.PageInterceptor"> <property name="properties"> <value> </value> </property> </bean> </array> </property> </bean> <!--Mybatis的Mapper文件识别 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.dodoke.tmall.mapper" /> </bean> <!--事务管理 --> <tx:annotation-driven transaction-manager="transactionManager" /> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans> ~~~ ## 步骤 6 : OrderService 新增方法 `add(Order c,List<OrderItem> ois);` ~~~ package com.dodoke.tmall.service; import java.util.List; import com.dodoke.tmall.pojo.Order; import com.dodoke.tmall.pojo.OrderItem; public interface OrderService { String waitPay = "waitPay"; String waitDelivery = "waitDelivery"; String waitConfirm = "waitConfirm"; String waitReview = "waitReview"; String finish = "finish"; String delete = "delete"; void add(Order c); void delete(int id); void update(Order c); Order get(int id); List list(); List list(int uid, String excludedStatus); float add(Order c,List<OrderItem> ois); } ~~~ ## 步骤 7 : OrderServiceImpl 实现`add(Order o, List<OrderItem> ois)`方法,该方法通过注解进行事务管理 ~~~ @Transactional(propagation= Propagation.REQUIRED,rollbackForClassName="Exception") ~~~ 下列代码用来模拟当增加订单后出现异常,观察事务管理是否预期发生。(需要把false修改为true才能观察到) ~~~ if(false) throw new RuntimeException(); ~~~ OrderServiceImpl.java: ~~~ package com.dodoke.tmall.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.dodoke.tmall.mapper.OrderMapper; import com.dodoke.tmall.pojo.Order; import com.dodoke.tmall.pojo.OrderExample; import com.dodoke.tmall.pojo.OrderItem; import com.dodoke.tmall.pojo.User; import com.dodoke.tmall.service.OrderItemService; import com.dodoke.tmall.service.OrderService; import com.dodoke.tmall.service.UserService; @Service public class OrderServiceImpl implements OrderService { @Autowired OrderMapper orderMapper; @Autowired UserService userService; @Autowired OrderItemService orderItemService; @Override public void add(Order c) { orderMapper.insert(c); } @Override public void delete(int id) { orderMapper.deleteByPrimaryKey(id); } @Override public void update(Order c) { orderMapper.updateByPrimaryKeySelective(c); } @Override public Order get(int id) { return orderMapper.selectByPrimaryKey(id); } public List<Order> list() { OrderExample example = new OrderExample(); example.setOrderByClause("id desc"); List<Order> result = orderMapper.selectByExample(example); setUser(result); return result; } public void setUser(List<Order> os) { for (Order o : os) { setUser(o); } } public void setUser(Order o) { int uid = o.getUserId(); User u = userService.get(uid); o.setUser(u); } @Override public List list(int uid, String excludedStatus) { OrderExample example = new OrderExample(); example.createCriteria().andUserIdEqualTo(uid).andStatusNotEqualTo(excludedStatus); example.setOrderByClause("id desc"); return orderMapper.selectByExample(example); } @Override @Transactional(propagation= Propagation.REQUIRED,rollbackForClassName="Exception") public float add(Order o, List<OrderItem> ois) { float total = 0; add(o); if(false) throw new RuntimeException(); for (OrderItem oi: ois) { oi.setOrderId(o.getId()); orderItemService.update(oi); total+=oi.getProduct().getPromotePrice()*oi.getNumber(); } return total; } } ~~~ ## 步骤 8 : ForeController.createOrder 提交订单访问路径 `/forecreateOrder`, 导致`ForeController.createOrder` 方法被调用。 1. 从session中获取user对象 2. 通过参数Order接受地址,邮编,收货人,用户留言等信息 3. 根据当前时间加上一个4位随机数生成订单号 4. 根据上述参数,创建订单对象 5. 把订单状态设置为等待支付 6. 从session中获取订单项集合 ( 在`结算功能的ForeController.buy() `中,订单项集合被放到了session中 ) 7. 把订单加入到数据库,并且遍历订单项集合,设置每个订单项的order,更新到数据库 8. 统计本次订单的总金额 9. 客户端跳转到确认支付页forealipay,并带上订单id和总金额 ~~~ package com.dodoke.tmall.controller; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import javax.servlet.http.HttpSession; import org.apache.commons.lang.math.RandomUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.util.HtmlUtils; import com.dodoke.tmall.comparator.ProductAllComparator; import com.dodoke.tmall.comparator.ProductDateComparator; import com.dodoke.tmall.comparator.ProductPriceComparator; import com.dodoke.tmall.comparator.ProductReviewComparator; import com.dodoke.tmall.comparator.ProductSaleCountComparator; import com.dodoke.tmall.pojo.Category; import com.dodoke.tmall.pojo.Order; import com.dodoke.tmall.pojo.OrderItem; import com.dodoke.tmall.pojo.Product; import com.dodoke.tmall.pojo.ProductImage; import com.dodoke.tmall.pojo.PropertyValue; import com.dodoke.tmall.pojo.Review; import com.dodoke.tmall.pojo.User; import com.dodoke.tmall.service.CategoryService; import com.dodoke.tmall.service.OrderItemService; import com.dodoke.tmall.service.OrderService; import com.dodoke.tmall.service.ProductImageService; import com.dodoke.tmall.service.ProductService; import com.dodoke.tmall.service.PropertyValueService; import com.dodoke.tmall.service.ReviewService; import com.dodoke.tmall.service.UserService; import com.github.pagehelper.PageHelper; @Controller @RequestMapping("") public class ForeController { @Autowired CategoryService categoryService; @Autowired ProductService productService; @Autowired UserService userService; @Autowired ProductImageService productImageService; @Autowired PropertyValueService propertyValueService; @Autowired OrderService orderService; @Autowired OrderItemService orderItemService; @Autowired ReviewService reviewService; @RequestMapping("forehome") public String home(Model model) { List<Category> cs = categoryService.list(); productService.fill(cs); productService.fillByRow(cs); model.addAttribute("cs", cs); return "fore/home"; } @RequestMapping("foreregister") public String register(Model model, User user) { String name = user.getName(); // 把账号里的特殊符号进行转义 name = HtmlUtils.htmlEscape(name); user.setName(name); boolean exist = userService.isExist(name); if (exist) { String m = "用户名已经被使用,不能使用"; model.addAttribute("msg", m); model.addAttribute("user", null); return "fore/register"; } userService.add(user); return "redirect:registerSuccessPage"; } @RequestMapping("forelogin") public String login(@RequestParam("name") String name, @RequestParam("password") String password, Model model, HttpSession session) { name = HtmlUtils.htmlEscape(name); User user = userService.get(name, password); if (null == user) { model.addAttribute("msg", "账号密码错误"); return "fore/login"; } session.setAttribute("user", user); return "redirect:forehome"; } @RequestMapping("forelogout") public String logout(HttpSession session) { session.removeAttribute("user"); return "redirect:forehome"; } @RequestMapping("foreproduct") public String product(int pid, Model model) { Product p = productService.get(pid); // 根据对象p,获取这个产品对应的单个图片集合 List<ProductImage> productSingleImages = productImageService.list(p.getId(), ProductImageService.type_single); // 根据对象p,获取这个产品对应的详情图片集合 List<ProductImage> productDetailImages = productImageService.list(p.getId(), ProductImageService.type_detail); p.setProductSingleImages(productSingleImages); p.setProductDetailImages(productDetailImages); // 获取产品的所有属性值 List<PropertyValue> pvs = propertyValueService.list(p.getId()); // 获取产品对应的所有的评价 List<Review> reviews = reviewService.list(p.getId()); // 设置产品的销量和评价数量 productService.setSaleAndReviewNumber(p); model.addAttribute("reviews", reviews); model.addAttribute("p", p); model.addAttribute("pvs", pvs); return "fore/product"; } @RequestMapping("forecheckLogin") @ResponseBody public String checkLogin(HttpSession session) { User user = (User) session.getAttribute("user"); if (null != user) { return "success"; } return "fail"; } @RequestMapping("foreloginAjax") @ResponseBody public String loginAjax(@RequestParam("name") String name, @RequestParam("password") String password, HttpSession session) { name = HtmlUtils.htmlEscape(name); User user = userService.get(name, password); if (null == user) { return "fail"; } session.setAttribute("user", user); return "success"; } @RequestMapping("forecategory") public String category(int cid, String sort, Model model) { Category c = categoryService.get(cid); productService.fill(c); productService.setSaleAndReviewNumber(c.getProducts()); if (null != sort) { switch (sort) { case "review": Collections.sort(c.getProducts(), new ProductReviewComparator()); break; case "date": Collections.sort(c.getProducts(), new ProductDateComparator()); break; case "saleCount": Collections.sort(c.getProducts(), new ProductSaleCountComparator()); break; case "price": Collections.sort(c.getProducts(), new ProductPriceComparator()); break; case "all": Collections.sort(c.getProducts(), new ProductAllComparator()); break; } } model.addAttribute("c", c); return "fore/category"; } @RequestMapping("foresearch") public String search(String keyword, Model model) { PageHelper.offsetPage(0, 20); List<Product> ps = productService.search(keyword); productService.setSaleAndReviewNumber(ps); model.addAttribute("ps", ps); return "fore/searchResult"; } @RequestMapping("forebuyone") public String buyone(int pid, int num, HttpSession session) { Product p = productService.get(pid); int oiid = 0; User user = (User) session.getAttribute("user"); boolean found = false; List<OrderItem> ois = orderItemService.listByUser(user.getId()); for (OrderItem oi : ois) { if (oi.getProduct().getId().intValue() == p.getId().intValue()) { oi.setNumber(oi.getNumber() + num); orderItemService.update(oi); found = true; oiid = oi.getId(); break; } } if (!found) { OrderItem oi = new OrderItem(); oi.setUserId(user.getId()); oi.setNumber(num); oi.setProductId(pid); orderItemService.add(oi); oiid = oi.getId(); } return "redirect:forebuy?oiid=" + oiid; } @RequestMapping("forebuy") public String buy(Model model, String[] oiid, HttpSession session) { List<OrderItem> ois = new ArrayList<>(); float total = 0; for (String strid : oiid) { int id = Integer.parseInt(strid); OrderItem oi = orderItemService.get(id); total += oi.getProduct().getPromotePrice() * oi.getNumber(); ois.add(oi); } session.setAttribute("ois", ois); model.addAttribute("total", total); return "fore/buy"; } @RequestMapping("foreaddCart") @ResponseBody public String addCart(int pid, int num, Model model, HttpSession session) { Product p = productService.get(pid); User user = (User) session.getAttribute("user"); boolean found = false; List<OrderItem> ois = orderItemService.listByUser(user.getId()); for (OrderItem oi : ois) { if (oi.getProduct().getId().intValue() == p.getId().intValue()) { oi.setNumber(oi.getNumber() + num); orderItemService.update(oi); found = true; break; } } if (!found) { OrderItem oi = new OrderItem(); oi.setUserId(user.getId()); oi.setNumber(num); oi.setProductId(pid); orderItemService.add(oi); } return "success"; } @RequestMapping("forecart") public String cart(Model model, HttpSession session) { User user = (User) session.getAttribute("user"); List<OrderItem> ois = orderItemService.listByUser(user.getId()); model.addAttribute("ois", ois); return "fore/cart"; } @RequestMapping("forechangeOrderItem") @ResponseBody public String changeOrderItem(Model model, HttpSession session, int pid, int number) { User user = (User) session.getAttribute("user"); if (null == user) { return "fail"; } List<OrderItem> ois = orderItemService.listByUser(user.getId()); for (OrderItem oi : ois) { if (oi.getProduct().getId().intValue() == pid) { oi.setNumber(number); orderItemService.update(oi); break; } } return "success"; } @RequestMapping("foredeleteOrderItem") @ResponseBody public String deleteOrderItem(Model model, HttpSession session, int oiid) { User user = (User) session.getAttribute("user"); if (null == user) { return "fail"; } orderItemService.delete(oiid); return "success"; } @RequestMapping("forebought") public String bought(Model model, HttpSession session) { User user = (User) session.getAttribute("user"); List<Order> os = orderService.list(user.getId(), OrderService.delete); orderItemService.fill(os); model.addAttribute("os", os); return "fore/bought"; } /** * 创建订单 * * @param model * @param order * 订单对象 * @param session * @return 页面路径字符串 */ @RequestMapping("forecreateOrder") public String createOrder(Model model, Order order, HttpSession session) { User user = (User) session.getAttribute("user"); // 生成订单号:年月日时分秒毫秒+随机数 String orderCode = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + RandomUtils.nextInt(10000); order.setOrderCode(orderCode); order.setCreateDate(new Date()); order.setUserId(user.getId()); order.setStatus(OrderService.waitPay); List<OrderItem> ois = (List<OrderItem>) session.getAttribute("ois"); float total = orderService.add(order, ois); return "redirect:forealipay?oid=" + order.getId() + "&total=" + total; } } ~~~ ## 步骤 9 : 确认支付页 1. 在上一步客户端跳转到路径/forealipay方法,导致PageController.alipay()方法被调用。 alipay()没做什么事情,就是服务端跳转到了alipay.jsp页面。 2. alipay.jsp: 与 register.jsp 相仿,alipay.jsp也包含了header.jsp, top.jsp, footer.jsp 等公共页面。 中间是确认支付业务页面 alipayPage.jsp 3. alipayPage.jsp: 显示总金额,并且让确认支付按钮跳转到页面 `/forepayed`页面,并带上oid和金额 ![](https://box.kancloud.cn/b8f0dce46bc66f55f5ef387da9061b62_257x405.png) ~~~ <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <div class="aliPayPageDiv"> <div class="aliPayPageLogo"> <img class="pull-left" src="img/site/simpleLogo.png"> <div style="clear: both"></div> </div> <div> <span class="confirmMoneyText">扫一扫付款(元)</span> <span class="confirmMoney"> ¥<fmt:formatNumber type="number" value="${param.total}" minFractionDigits="2" /></span> </div> <div> <img class="aliPayImg" src="img/site/alipay2wei.png"> </div> <div> <a href="forepayed?oid=${param.oid}&total=${param.total}"><button class="confirmPay">确认支付</button></a> </div> </div> ~~~ ## 步骤 10 : 支付成功页 1. 在上一步确认访问按钮提交数据到`/forepayed`,导致`ForeController.payed`方法被调用 1.1 获取参数oid 1.2 根据oid获取到订单对象order 1.3 修改订单对象的状态和支付时间 1.4 更新这个订单对象到数据库 1.5 把这个订单对象放在model的属性"o"上 1.6 服务端跳转到payed.jsp 2. payed.jsp 与 register.jsp 相仿,payed.jsp也包含了header.jsp, top.jsp, simpleSearch.jsp, footer.jsp 等公共页面。 中间是支付成功业务页面 payedPage.jsp 3. payedPage.jsp 显示订单中的地址,邮编,收货人,手机号码等等 ![](https://box.kancloud.cn/1d6b04036d257bdb7513ad5a9e405641_1284x367.png) payed方法: ~~~ @RequestMapping("forepayed") public String payed(int oid, float total, Model model) { Order order = orderService.get(oid); order.setStatus(OrderService.waitDelivery); order.setPayDate(new Date()); orderService.update(order); model.addAttribute("o", order); return "fore/payed"; } ~~~ payed.jsp: ~~~ <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix='fmt' uri="http://java.sun.com/jsp/jstl/fmt"%> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> <%@include file="../include/fore/header.jsp"%> <%@include file="../include/fore/top.jsp"%> <%@include file="../include/fore/simpleSearch.jsp"%> <%@include file="../include/fore/cart/payedPage.jsp"%> <%@include file="../include/fore/footer.jsp"%> ~~~ payedPage.jsp: ~~~ <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <div class="payedDiv"> <div class="payedTextDiv"> <img src="img/site/paySuccess.png"> <span>您已成功付款</span> </div> <div class="payedAddressInfo"> <ul> <li>收货地址:${o.address} ${o.receiver} ${o.mobile }</li> <li>实付款:<span class="payedInfoPrice"> ¥<fmt:formatNumber type="number" value="${param.total}" minFractionDigits="2" /></li> <li>预计08月08日送达</li> </ul> <div class="paedCheckLinkDiv"> 您可以 <a class="payedCheckLink" href="forebought">查看已买到的宝贝</a> <a class="payedCheckLink" href="forebought">查看交易详情 </a> </div> </div> <div class="payedSeperateLine"></div> <div class="warningDiv"> <img src="img/site/warning.png"> <b>安全提醒:</b>下单后,<span class="redColor boldWord">用QQ给您发送链接办理退款的都是骗子!</span>天猫不存在系统升级,订单异常等问题,谨防假冒客服电话诈骗! </div> </div> ~~~ ForeController: ~~~ package com.dodoke.tmall.controller; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import javax.servlet.http.HttpSession; import org.apache.commons.lang.math.RandomUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.util.HtmlUtils; import com.dodoke.tmall.comparator.ProductAllComparator; import com.dodoke.tmall.comparator.ProductDateComparator; import com.dodoke.tmall.comparator.ProductPriceComparator; import com.dodoke.tmall.comparator.ProductReviewComparator; import com.dodoke.tmall.comparator.ProductSaleCountComparator; import com.dodoke.tmall.pojo.Category; import com.dodoke.tmall.pojo.Order; import com.dodoke.tmall.pojo.OrderItem; import com.dodoke.tmall.pojo.Product; import com.dodoke.tmall.pojo.ProductImage; import com.dodoke.tmall.pojo.PropertyValue; import com.dodoke.tmall.pojo.Review; import com.dodoke.tmall.pojo.User; import com.dodoke.tmall.service.CategoryService; import com.dodoke.tmall.service.OrderItemService; import com.dodoke.tmall.service.OrderService; import com.dodoke.tmall.service.ProductImageService; import com.dodoke.tmall.service.ProductService; import com.dodoke.tmall.service.PropertyValueService; import com.dodoke.tmall.service.ReviewService; import com.dodoke.tmall.service.UserService; import com.github.pagehelper.PageHelper; @Controller @RequestMapping("") public class ForeController { @Autowired CategoryService categoryService; @Autowired ProductService productService; @Autowired UserService userService; @Autowired ProductImageService productImageService; @Autowired PropertyValueService propertyValueService; @Autowired OrderService orderService; @Autowired OrderItemService orderItemService; @Autowired ReviewService reviewService; @RequestMapping("forehome") public String home(Model model) { List<Category> cs = categoryService.list(); productService.fill(cs); productService.fillByRow(cs); model.addAttribute("cs", cs); return "fore/home"; } @RequestMapping("foreregister") public String register(Model model, User user) { String name = user.getName(); // 把账号里的特殊符号进行转义 name = HtmlUtils.htmlEscape(name); user.setName(name); boolean exist = userService.isExist(name); if (exist) { String m = "用户名已经被使用,不能使用"; model.addAttribute("msg", m); model.addAttribute("user", null); return "fore/register"; } userService.add(user); return "redirect:registerSuccessPage"; } @RequestMapping("forelogin") public String login(@RequestParam("name") String name, @RequestParam("password") String password, Model model, HttpSession session) { name = HtmlUtils.htmlEscape(name); User user = userService.get(name, password); if (null == user) { model.addAttribute("msg", "账号密码错误"); return "fore/login"; } session.setAttribute("user", user); return "redirect:forehome"; } @RequestMapping("forelogout") public String logout(HttpSession session) { session.removeAttribute("user"); return "redirect:forehome"; } @RequestMapping("foreproduct") public String product(int pid, Model model) { Product p = productService.get(pid); // 根据对象p,获取这个产品对应的单个图片集合 List<ProductImage> productSingleImages = productImageService.list(p.getId(), ProductImageService.type_single); // 根据对象p,获取这个产品对应的详情图片集合 List<ProductImage> productDetailImages = productImageService.list(p.getId(), ProductImageService.type_detail); p.setProductSingleImages(productSingleImages); p.setProductDetailImages(productDetailImages); // 获取产品的所有属性值 List<PropertyValue> pvs = propertyValueService.list(p.getId()); // 获取产品对应的所有的评价 List<Review> reviews = reviewService.list(p.getId()); // 设置产品的销量和评价数量 productService.setSaleAndReviewNumber(p); model.addAttribute("reviews", reviews); model.addAttribute("p", p); model.addAttribute("pvs", pvs); return "fore/product"; } @RequestMapping("forecheckLogin") @ResponseBody public String checkLogin(HttpSession session) { User user = (User) session.getAttribute("user"); if (null != user) { return "success"; } return "fail"; } @RequestMapping("foreloginAjax") @ResponseBody public String loginAjax(@RequestParam("name") String name, @RequestParam("password") String password, HttpSession session) { name = HtmlUtils.htmlEscape(name); User user = userService.get(name, password); if (null == user) { return "fail"; } session.setAttribute("user", user); return "success"; } @RequestMapping("forecategory") public String category(int cid, String sort, Model model) { Category c = categoryService.get(cid); productService.fill(c); productService.setSaleAndReviewNumber(c.getProducts()); if (null != sort) { switch (sort) { case "review": Collections.sort(c.getProducts(), new ProductReviewComparator()); break; case "date": Collections.sort(c.getProducts(), new ProductDateComparator()); break; case "saleCount": Collections.sort(c.getProducts(), new ProductSaleCountComparator()); break; case "price": Collections.sort(c.getProducts(), new ProductPriceComparator()); break; case "all": Collections.sort(c.getProducts(), new ProductAllComparator()); break; } } model.addAttribute("c", c); return "fore/category"; } @RequestMapping("foresearch") public String search(String keyword, Model model) { PageHelper.offsetPage(0, 20); List<Product> ps = productService.search(keyword); productService.setSaleAndReviewNumber(ps); model.addAttribute("ps", ps); return "fore/searchResult"; } @RequestMapping("forebuyone") public String buyone(int pid, int num, HttpSession session) { Product p = productService.get(pid); int oiid = 0; User user = (User) session.getAttribute("user"); boolean found = false; List<OrderItem> ois = orderItemService.listByUser(user.getId()); for (OrderItem oi : ois) { if (oi.getProduct().getId().intValue() == p.getId().intValue()) { oi.setNumber(oi.getNumber() + num); orderItemService.update(oi); found = true; oiid = oi.getId(); break; } } if (!found) { OrderItem oi = new OrderItem(); oi.setUserId(user.getId()); oi.setNumber(num); oi.setProductId(pid); orderItemService.add(oi); oiid = oi.getId(); } return "redirect:forebuy?oiid=" + oiid; } @RequestMapping("forebuy") public String buy(Model model, String[] oiid, HttpSession session) { List<OrderItem> ois = new ArrayList<>(); float total = 0; for (String strid : oiid) { int id = Integer.parseInt(strid); OrderItem oi = orderItemService.get(id); total += oi.getProduct().getPromotePrice() * oi.getNumber(); ois.add(oi); } session.setAttribute("ois", ois); model.addAttribute("total", total); return "fore/buy"; } @RequestMapping("foreaddCart") @ResponseBody public String addCart(int pid, int num, Model model, HttpSession session) { Product p = productService.get(pid); User user = (User) session.getAttribute("user"); boolean found = false; List<OrderItem> ois = orderItemService.listByUser(user.getId()); for (OrderItem oi : ois) { if (oi.getProduct().getId().intValue() == p.getId().intValue()) { oi.setNumber(oi.getNumber() + num); orderItemService.update(oi); found = true; break; } } if (!found) { OrderItem oi = new OrderItem(); oi.setUserId(user.getId()); oi.setNumber(num); oi.setProductId(pid); orderItemService.add(oi); } return "success"; } @RequestMapping("forecart") public String cart(Model model, HttpSession session) { User user = (User) session.getAttribute("user"); List<OrderItem> ois = orderItemService.listByUser(user.getId()); model.addAttribute("ois", ois); return "fore/cart"; } @RequestMapping("forechangeOrderItem") @ResponseBody public String changeOrderItem(Model model, HttpSession session, int pid, int number) { User user = (User) session.getAttribute("user"); if (null == user) { return "fail"; } List<OrderItem> ois = orderItemService.listByUser(user.getId()); for (OrderItem oi : ois) { if (oi.getProduct().getId().intValue() == pid) { oi.setNumber(number); orderItemService.update(oi); break; } } return "success"; } @RequestMapping("foredeleteOrderItem") @ResponseBody public String deleteOrderItem(Model model, HttpSession session, int oiid) { User user = (User) session.getAttribute("user"); if (null == user) { return "fail"; } orderItemService.delete(oiid); return "success"; } @RequestMapping("forebought") public String bought(Model model, HttpSession session) { User user = (User) session.getAttribute("user"); List<Order> os = orderService.list(user.getId(), OrderService.delete); orderItemService.fill(os); model.addAttribute("os", os); return "fore/bought"; } /** * 创建订单 * * @param model * @param order * 订单对象 * @param session * @return 页面路径字符串 */ @RequestMapping("forecreateOrder") public String createOrder(Model model, Order order, HttpSession session) { User user = (User) session.getAttribute("user"); // 生成订单号:年月日时分秒毫秒+随机数 String orderCode = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + RandomUtils.nextInt(10000); order.setOrderCode(orderCode); order.setCreateDate(new Date()); order.setUserId(user.getId()); order.setStatus(OrderService.waitPay); List<OrderItem> ois = (List<OrderItem>) session.getAttribute("ois"); float total = orderService.add(order, ois); return "redirect:forealipay?oid=" + order.getId() + "&total=" + total; } @RequestMapping("forepayed") public String payed(int oid, float total, Model model) { Order order = orderService.get(oid); order.setStatus(OrderService.waitDelivery); order.setPayDate(new Date()); orderService.update(order); model.addAttribute("o", order); return "fore/payed"; } } ~~~