文章目录
一、前言
近几天有个同粉丝让我写一个《吃货联盟外卖系统》,主要有两个模块,然后使用技术为SSM+jsp,我晚上下班没有事情,就帮粉丝做了一个,主要是商家模块和用户模块,然后今天将项目发布出来,供大家参考!
然后有粉丝就问我,在哪里有那么多时间写这些项目,回答是:永远记住一点,编程最终要服务于实际生活和工作。真正理解好面向对象思维,才能做好开发。在做编程题的时候,如何将所学到的技能应用到实处,是学习编程非常重要的关键点,不然学了那么多知识点,堆积在大脑里面反而会成为负累!要做到这一点,就需要平时多结合生活工作中的事物去思考和理解,比如你逛超市,看到一排排的货架放满了各种商品,这些商品用程序来描述就是object,他们为什么会被放到一起?因为他们有相同的attribute和behavior,属于同一个class。很多同学根本就不知道学编程干什么,只是有空看看视频,最起码的概念都没有,自然是与就业永远搭不上边。
演示视频
SSM+JSP的吃货联盟外卖系统
二、数据库及核心源码
1、数据库设计文档
数据库名: takeaway
文档版本: V1.0.0
文档描述: 吃货联盟外卖系统数据库表设计描述
表名: admin
说明: 管理员
数据列:
表名: category
说明: 餐厅
数据列:
表名: food
说明: 食物
数据列:
表名: merchant
说明: 商品
数据列:
表名: orderitem
说明: 订单
数据列:
表名: orders
说明: 订单
数据列:
表名: user
说明: 用户
数据列:
2、数据库SQL
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for admin -- ---------------------------- DROP TABLE IF EXISTS `admin`; CREATE TABLE `admin` ( `aid` int NOT NULL AUTO_INCREMENT, `aname` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `apassword` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, PRIMARY KEY (`aid`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for category -- ---------------------------- DROP TABLE IF EXISTS `category`; CREATE TABLE `category` ( `cid` int NOT NULL AUTO_INCREMENT, `cname` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, PRIMARY KEY (`cid`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for food -- ---------------------------- DROP TABLE IF EXISTS `food`; CREATE TABLE `food` ( `fid` int NOT NULL AUTO_INCREMENT, `fname` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `price` decimal(10, 2) NULL DEFAULT NULL, `fimage` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `mid` int NULL DEFAULT NULL, PRIMARY KEY (`fid`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for merchant -- ---------------------------- DROP TABLE IF EXISTS `merchant`; CREATE TABLE `merchant` ( `mid` int NOT NULL AUTO_INCREMENT, `mname` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `mimage` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `cid` int NULL DEFAULT NULL, PRIMARY KEY (`mid`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for orderitem -- ---------------------------- DROP TABLE IF EXISTS `orderitem`; CREATE TABLE `orderitem` ( `iid` int NOT NULL AUTO_INCREMENT, `count` int NULL DEFAULT NULL, `subtotal` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `oid` int NULL DEFAULT NULL, `fid` int NULL DEFAULT NULL, PRIMARY KEY (`iid`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for orders -- ---------------------------- DROP TABLE IF EXISTS `orders`; CREATE TABLE `orders` ( `oid` int NOT NULL AUTO_INCREMENT, `ordertime` datetime(0) NULL DEFAULT NULL, `total` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `state` int NULL DEFAULT NULL, `uid` int NULL DEFAULT NULL, `address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `phone` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, PRIMARY KEY (`oid`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for user -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `uid` int NOT NULL AUTO_INCREMENT, `username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `balance` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, PRIMARY KEY (`uid`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1;
3、resources
Spring配置文件
<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 自动扫描使用@Service注解的类 --> <context:component-scan base-package="com.jh.*.service"></context:component-scan> <!-- 整合mybatis --> <!-- 引入db.properties --> <context:property-placeholder file-encoding="utf-8" location="classpath:db.properties"/> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="driverClassName" value="${jdbc.driver}"/> </bean> <!-- 扫描mapper的配置文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <!-- 扫描mapper的接口 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.jh.*.dao"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置基于注解的声明式事务 --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
Spring-MVC配置文件
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- springMVC的自动扫描--> <context:component-scan base-package="com.jh.*.controller"></context:component-scan> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/page/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 引用静态资源的--> <mvc:default-servlet-handler/> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg> <value>UTF-8</value> </constructor-arg> </bean> </mvc:message-converters> </mvc:annotation-driven> <context:annotation-config></context:annotation-config> <!--配置springMVC的上传 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"/> <property name="maxUploadSize" value="10000000"/> </bean> </beans>
log4j文件
#loggers log4j.rootLogger=DEBUG log4j.logger.com.atguigu=DEBUG,console,LogFile log4j.logger.test.com.apollo=DEBUG,console,LogFile log4j.logger.com.apache=DEBUG,console,LogFile log4j.logger.com.ibatis=DEBUG,console,LogFile log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG,console,LogFile log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG,console,LogFile log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG,console,LogFile log4j.logger.java.sql.Connection=DEBUG,console,LogFile log4j.logger.java.sql.Statement=DEBUG,console,LogFile log4j.logger.java.sql.PreparedStatement=DEBUG,console,LogFile log4j.logger.org.springframework=error,console,LogFile #default logfile config log4j.appender.LogFile=org.apache.log4j.DailyRollingFileAppender log4j.appender.LogFile.file=../log/jf-console.log log4j.appender.LogFile.Encoding=UTF-8 log4j.appender.LogFile.DatePattern='.'yyyy-MM-dd log4j.appender.LogFile.layout=org.apache.log4j.PatternLayout log4j.appender.LogFile.layout.ConversionPattern=[%d] [%t] (%F\:%L) %-5p %c - %m%n #console output config log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=[%d] [%t] (%F\:%L) %-5p %c - %m%n
db.properties
jdbc.url=jdbc:mysql://127.0.0.1:3306/takeaway?useSSL=false&serverTimezone=UTC jdbc.username=root jdbc.password=root jdbc.driver= com.mysql.cj.jdbc.Driver
4、mapper文件
admin
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.jh.admin.dao.AdminDao"> <resultMap id="Admin" type="com.jh.entity.Admin"> <id column="aid" property="aid" jdbcType="BIGINT" /> <result column="aname" property="aname" jdbcType="VARCHAR"/> <result column="apassword" property="apassword" jdbcType="VARCHAR"/> </resultMap> <select id="selectByNameAndPwd" resultMap="Admin" parameterType="String"> SELECT * FROM admin WHERE aname = #{username} <if test="password != null"> and apassword = #{password} </if> </select> <resultMap id="Merchant" type="com.jh.entity.Merchant"> <id column="mid" property="mid" jdbcType="BIGINT" /> <result column="mname" property="mname" jdbcType="VARCHAR"/> <result column="mimage" property="mimage" jdbcType="VARCHAR"/> <result column="cid" property="cid" jdbcType="BIGINT"/> </resultMap> <select id="selectFindAllMerchant" resultMap="Merchant"> SELECT * FROM merchant </select> <select id="selectFindMerchant" resultMap="Merchant" > SELECT * FROM merchant WHERE cid = ${cid} </select> <resultMap id="Category" type="com.jh.entity.Category"> <id column="cid" property="cid" jdbcType="BIGINT"/> <result column="cname" property="cname" jdbcType="VARCHAR"/> </resultMap> <select id="findAllCategory" resultMap="Category"> SELECT * FROM category </select> <insert id="addMerchant" parameterType="com.jh.entity.Merchant"> INSERT INTO merchant(mname,mimage,cid) VALUES(#{mname,jdbcType=VARCHAR},#{mimage,jdbcType=VARCHAR},#{cid,jdbcType=BIGINT}) </insert> <resultMap id="Orders" type="com.jh.entity.Orders"> <id column="oid" property="oid" jdbcType="BIGINT"/> <result column="ordertime" property="ordertime" jdbcType="TIMESTAMP"/> <result column="total" property="total" jdbcType="DECIMAL"/> <result column="state" property="state" jdbcType="TINYINT"/> <result column="uid" property="uid" jdbcType="BIGINT"/> <result column="address" property="address" jdbcType="VARCHAR"/> <result column="phone" property="phone" jdbcType="VARCHAR"/> </resultMap> <select id="findAllOrders" resultMap="Orders"> SELECT * FROM orders </select> <select id="findOrder" resultMap="Orders"> SELECT * FROM orders WHERE oid = ${oid} </select> <resultMap id="OrderItem" type="com.jh.entity.OrderItem"> <id column="iid" property="iid" jdbcType="BIGINT"/> <result column="count" property="count" jdbcType="TINYINT"/> <result column="subtotal" property="subtotal" jdbcType="DECIMAL"/> <result column="oid" property="oid" jdbcType="BIGINT"/> <result column="fid" property="fid" jdbcType="BIGINT"/> </resultMap> <select id="findOrders" resultMap="OrderItem"> SELECT * FROM orderitem WHERE oid=${oid} </select> <insert id="addFood" parameterType="com.jh.entity.Food"> INSERT INTO food(fname,price,mid,fimage) VALUE(#{fname,jdbcType=VARCHAR},#{price,jdbcType=DECIMAL}, #{mid,jdbcType=BIGINT},#{fimage,jdbcType=VARCHAR}) </insert> <resultMap id="Food" type="com.jh.entity.Food"> <id column="fid" property="fid" jdbcType="BIGINT"/> <result column="fname" property="fname" jdbcType="VARCHAR"/> <result column="price" property="price" jdbcType="DECIMAL"/> <result column="fimage" property="fimage" jdbcType="VARCHAR"/> <result column="mid" property="mid" jdbcType="BIGINT"/> </resultMap> <select id="findFoodDetail" resultMap="Food"> SELECT * FROM food WHERE mid=${mid} </select> <delete id="deleteMerchant" parameterType="java.lang.Long"> DELETE FROM merchant WHERE mid=${mid} </delete> <delete id="deleteFood" parameterType="java.lang.Long"> DELETE FROM food WHERE fid=${fid} </delete> </mapper>
user
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.jh.user.dao.UserDao"> <resultMap id="User" type="com.jh.entity.User"> <id column="uid" property="uid" jdbcType="BIGINT" /> <result column="username" property="username" jdbcType="VARCHAR"/> <result column="password" property="password" jdbcType="VARCHAR"/> <result column="email" property="email" jdbcType="VARCHAR"/> <result column="code" property="code" jdbcType="CHAR"/> <result column="state" property="state" jdbcType="TINYINT"/> <result column="balance" property="balance" jdbcType="DECIMAL"/> </resultMap> <select id="selectByNameAndPwd" resultMap="User" parameterType="String"> SELECT * FROM user WHERE username = #{username} <if test="password != null"> and password = #{password} </if> </select> <resultMap id="Merchant" type="com.jh.entity.Merchant"> <id column="mid" property="mid" jdbcType="BIGINT" /> <result column="mname" property="mname" jdbcType="VARCHAR"/> <result column="mimage" property="mimage" jdbcType="VARCHAR"/> <result column="cid" property="cid" jdbcType="BIGINT"/> </resultMap> <select id="findMerchant" resultMap="Merchant" > SELECT * FROM merchant WHERE cid = ${cid} </select> <resultMap id="Food" type="com.jh.entity.Food"> <id column="fid" property="fid" jdbcType="BIGINT"/> <result column="fname" property="fname" jdbcType="VARCHAR"/> <result column="price" property="price" jdbcType="DECIMAL"/> <result column="fimage" property="fimage" jdbcType="VARCHAR"/> <result column="mid" property="mid" jdbcType="BIGINT"/> </resultMap> <select id="findFoodDetail" resultMap="Food"> SELECT * FROM food WHERE mid=${mid} </select> <select id="findFood" resultMap="Food"> SELECT * FROM food WHERE fid=${fid} </select> <insert id="addOrder" parameterType="com.jh.entity.Orders"> INSERT INTO orders(oid,ordertime,total,state,uid,address,phone) VALUE(#{oid,jdbcType=BIGINT},#{ordertime,jdbcType=TIMESTAMP},#{total,jdbcType=DECIMAL},#{state,jdbcType=TINYINT}, #{uid,jdbcType=BIGINT},#{address,jdbcType=VARCHAR},#{phone,jdbcType=VARCHAR}) </insert> <insert id="addOrderItem" parameterType="com.jh.entity.OrderItem"> INSERT INTO orderitem(count,subtotal,oid,fid) VALUE(#{count,jdbcType=INTEGER},#{subtotal,jdbcType=DECIMAL}, #{oid,jdbcType=BIGINT},#{fid,jdbcType=BIGINT}) </insert> <resultMap id="Orders" type="com.jh.entity.Orders"> <id column="oid" property="oid" jdbcType="BIGINT"/> <result column="ordertime" property="ordertime" jdbcType="TIMESTAMP"/> <result column="total" property="total" jdbcType="DECIMAL"/> <result column="state" property="state" jdbcType="TINYINT"/> <result column="uid" property="uid" jdbcType="BIGINT"/> <result column="address" property="address" jdbcType="VARCHAR"/> <result column="phone" property="phone" jdbcType="VARCHAR"/> </resultMap> <select id="findOrder" resultMap="Orders"> SELECT * FROM orders WHERE oid = ${oid} </select> <select id="findOrders" resultMap="Orders"> SELECT * FROM orders WHERE uid = ${uid} </select> <update id="pay"> UPDATE user SET balance = balance - ${total} WHERE uid = ${uid} </update> <update id="over"> UPDATE orders SET state = 2 WHERE oid = ${oid} </update> <resultMap id="OrderItem" type="com.jh.entity.OrderItem"> <id column="iid" property="iid" jdbcType="BIGINT"/> <result column="count" property="count" jdbcType="TINYINT"/> <result column="subtotal" property="subtotal" jdbcType="DECIMAL"/> <result column="oid" property="oid" jdbcType="BIGINT"/> <result column="fid" property="fid" jdbcType="BIGINT"/> </resultMap> <select id="orderDetail" resultMap="OrderItem"> SELECT * FROM orderitem WHERE oid = ${oid} </select> </mapper>
5、核心代码
AdminController
package com.jh.admin.controller; import com.alibaba.fastjson.JSONObject; import com.jh.admin.service.AdminService; import com.jh.entity.*; import org.apache.commons.io.FilenameUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.commons.CommonsMultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.File; import java.util.List; import java.util.UUID; @Controller @RequestMapping(value = "admin") public class AdminController { @Autowired AdminService adminService; /** * 管理员登录页面 */ @RequestMapping(value = "login",method=RequestMethod.POST) public String login(@RequestParam("username") String username, @RequestParam("password") String password, HttpSession session, RedirectAttributes redirectAttributes) throws Exception { //2.验证用户名和密码 Admin admin = new Admin(); admin.setAname(username); admin.setApassword(password); Admin adminLogin = adminService.selectByNameAndPwd(username,password); //用户名或密码失败的情况下 if(adminLogin == null){ redirectAttributes.addFlashAttribute("errMsg","用户名或密码错误!"); System.out.println("用户名或密码错误"); return "redirect:/admin/login2"; } //放入用户实体到Session中 session.setAttribute("adminLogin",adminLogin); return "admin/index"; } /** * 用于配合管理员登录页面的错误反馈 * redirectAttributes.addFlashAttribute("errMsg","用户名或密码错误!"); * 需要先重定向至controller再跳转才能传递参数 * @return */ @RequestMapping(value = "login2") public String redirect()throws Exception{ return "admin/login"; } /** * 退出功能 * @param session * @return * @throws Exception */ @RequestMapping(value = "logout") public String logout(HttpSession session)throws Exception{ session.invalidate(); return "admin/login"; } /** * 查询所有店铺 * @param session * @return * @throws Exception */ @RequestMapping(value = "findAll") public String selectFindAllMerchant(HttpSession session) throws Exception{ List<Merchant> list = adminService.selectFindAllMerchant(); session.setAttribute("list",list); return "admin/list"; } /** * 查询餐厅分类 * @param session * @return * @throws Exception */ @RequestMapping(value = "findAllCategory") public String findAllCategory(HttpSession session)throws Exception{ List<Category> list1 = adminService.findAllCategory(); session.setAttribute("list1",list1); return "admin/body"; } /** * 添加店铺 * @param merchant * @throws Exception */ @RequestMapping(value = "addMerchant",method=RequestMethod.POST) public String addMerchant(Merchant merchant, RedirectAttributes redirectAttributes, @RequestParam("file") CommonsMultipartFile file, HttpServletRequest request)throws Exception{ Merchant mer = new Merchant(); //通过相对路径,获取上传文件路径 String realPath = request.getSession().getServletContext().getRealPath("/merchant_image"); System.out.println("真实路径:" + realPath); // 获取文件原始名称 original:[əˈrɪdʒənl] 原创的 String originalFilename = file.getOriginalFilename(); //获取文件的后缀名 String extension = FilenameUtils.getExtension(originalFilename); //uuid的字符串 String uuid = UUID.randomUUID().toString(); //拼接UUID形式的文件名 String newFileName = uuid.replace("-","")+"."+extension; // 上传文件到服务器 transfer:[trænsˈfɜː] 转移 mer.setMname(merchant.getMname()); mer.setMimage(newFileName); mer.setCid(merchant.getCid()); try{ file.transferTo(new java.io.File(realPath+"/"+ newFileName)); int i = adminService.addMerchant(mer); if(i <= 0){ redirectAttributes.addFlashAttribute("Msg","添加失败"); } else{ redirectAttributes.addFlashAttribute("Msg","添加成功"); } }catch(Exception e){ e.printStackTrace(); } return "redirect:/admin/findAll"; } /** * 查询所有订单 * @param session * @return * @throws Exception */ @RequestMapping(value = "findAllOrders") public String findAllOrders(HttpSession session)throws Exception{ List<Orders> list2 = adminService.findAllOrders(); session.setAttribute("list2",list2); return "admin/orders"; } /** * 查询订单详细信息 * @return * @throws Exception */ @RequestMapping(value = "findOrders") public String findOrders(@RequestParam("oid") long oid, HttpSession session)throws Exception{ Orders order = adminService.findOrder(oid); session.setAttribute("order",order); List<OrderItem> list3 = adminService.findOrders(oid); session.setAttribute("list3",list3); return "admin/orderItem"; } /** * 查询餐厅分类 * @param session * @return * @throws Exception */ @RequestMapping(value = "findCategory") public String findCategory(HttpSession session)throws Exception{ List<Category> list3 = adminService.findAllCategory(); session.setAttribute("list3",list3); return "admin/food"; } /** * 查询店铺 * @param cid * @return * @throws Exception */ @ResponseBody @RequestMapping(value = "findMerchant",method = RequestMethod.POST) public List<Merchant> selectFindMerchant(@RequestParam("cid") long cid)throws Exception{ List<Merchant> list4 = adminService.selectFindMerchant(cid); return list4; } /** * 添加食物 * @param food * @param redirectAttributes * @param file * @param request * @return * @throws Exception */ @RequestMapping(value = "addFood",method = RequestMethod.POST) public String addFood(Food food, RedirectAttributes redirectAttributes, @RequestParam("file") CommonsMultipartFile file, HttpServletRequest request)throws Exception{ //通过相对路径,获取上传文件路径 String realPath = request.getSession().getServletContext().getRealPath("/food_image"); System.out.println("真实路径:" + realPath); // 获取文件原始名称 original:[əˈrɪdʒənl] 原创的 String originalFilename = file.getOriginalFilename(); //获取文件的后缀名 String extension = FilenameUtils.getExtension(originalFilename); //uuid的字符串 String uuid = UUID.randomUUID().toString(); //拼接UUID形式的文件名 String newFileName = uuid.replace("-","")+"."+extension; Food f = new Food(); f.setFname(food.getFname()); f.setPrice(food.getPrice()); f.setMid(food.getMid()); f.setFimage(newFileName); try{ file.transferTo(new java.io.File(realPath+"/"+ newFileName)); int i = adminService.addFood(f); if(i <= 0){ redirectAttributes.addFlashAttribute("msg","添加失败"); } else{ redirectAttributes.addFlashAttribute("msg","添加成功"); } }catch(Exception e){ e.printStackTrace(); } return "redirect:/admin/findCategory"; } /** * 查看食物 * @param mid * @param session * @return * @throws Exception */ @RequestMapping(value = "findFoodDetail") public String findFoodDetail(@RequestParam("mid") long mid, HttpSession session)throws Exception{ List<Food> list5 = adminService.findFoodDetail(mid); session.setAttribute("list5",list5); return "admin/foodDetail"; } /** * 删除店铺 * @param mid * @param redirectAttributes * @return * @throws Exception */ @ResponseBody @RequestMapping(value = "deleteMerchant",method = RequestMethod.POST) public JSONObject deleteMerchant(@RequestParam("mid") long mid, RedirectAttributes redirectAttributes)throws Exception{ JSONObject j = new JSONObject(); int i = adminService.deleteMerchant(mid); if(i <= 0){ j.put("mmsg","删除失败"); return j; } j.put("mmsg","删除成功"); return j; } /** * 删除食物 * @param fid * @param redirectAttributes * @return * @throws Exception */ @ResponseBody @RequestMapping(value = "deleteFood",method = RequestMethod.POST) public JSONObject deleteFood(@RequestParam("fid") long fid, RedirectAttributes redirectAttributes)throws Exception{ JSONObject s = new JSONObject(); int i = adminService.deleteFood(fid); if(i <= 0){ s.put("mmsg","删除失败"); return s; } s.put("mmsg","删除成功"); return s; } }
UserController
package com.jh.user.controller; import com.jh.user.cart.Cart; import com.jh.entity.*; import com.jh.user.cart.CartItem; import com.jh.user.service.UserService; import com.jh.user.util.Uuid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; @Controller @RequestMapping(value = "user") public class UserController { @Autowired UserService userService; /** * 用户登录 * @param username * @param password * @param session * @param redirectAttributes * @return * @throws Exception */ @RequestMapping(value = "login",method = RequestMethod.POST) public String selectByNameAndPwd(@RequestParam("username") String username, @RequestParam("password") String password, HttpSession session, RedirectAttributes redirectAttributes)throws Exception{ User user = userService.selectByNameAndPwd(username,password); //验证用户名密码失败时 if(user == null){ redirectAttributes.addFlashAttribute("errMsg","用户名或密码错误"); return "redirect:/user/login2"; } //将用户信息放入实体中 session.setAttribute("user",user); return "user/index"; } @RequestMapping(value = "login2") public String redirect(){ return "user/login"; } /** * 用户退出 * @param session * @return * @throws Exception */ @RequestMapping(value = "logout") public String logout(HttpSession session)throws Exception{ //销毁session session.invalidate(); return "user/login"; } /** * 查询店铺 * @param cid * @param session * @return */ @RequestMapping(value = "findMerchant") public String findMerchant(@RequestParam("cid") long cid,HttpSession session){ List<Merchant> list = userService.findMerchant(cid); session.setAttribute("list",list); return "user/list"; } /** * 用户查询食物 * @param session * @return * @throws Exception */ @RequestMapping(value = "findFoodDetail") public String findFoodDetail(@RequestParam("mid") long mid, HttpSession session)throws Exception{ List<Food> list2 = userService.findFoodDetail(mid); session.setAttribute("list2",list2); return "user/foodDetail"; } /** * 添加到购物车 * @param request * @param fid * @return * @throws Exception */ @RequestMapping(value = "addCart") public String addCart(HttpServletRequest request, @RequestParam("fid") long fid)throws Exception{ int count = 1; Cart cart = (Cart)request.getSession().getAttribute("cart"); if(cart == null){ cart = new Cart(); request.getSession().setAttribute("cart",cart); } Food food = userService.findFood(fid); CartItem cartItem = new CartItem(); cartItem.setFood(food); cartItem.setCount(count); cart.add(cartItem); return "user/cart"; } /** * 删除指定条目 * @param fid * @param request * @return * @throws Exception */ @RequestMapping(value = "delete") public String delete(long fid,HttpServletRequest request)throws Exception{ Cart cart = (Cart)request.getSession().getAttribute("cart"); cart.delete(fid); return "user/cart"; } /** * 清空购物车 * @param request * @return * @throws Exception */ @RequestMapping(value = "deleteAll") public String deleteAll(HttpServletRequest request)throws Exception{ Cart cart = (Cart)request.getSession().getAttribute("cart"); cart.clear(); return "user/cart"; } /** * 判断用户余额是否充足 * @param session * @param request * @return * @throws Exception */ @RequestMapping(value = "judge") public String judge(HttpSession session,HttpServletRequest request)throws Exception{ //从session中获取用户账户余额 User user = (User)session.getAttribute("user"); float balance = user.getBalance(); //获取购物车商品总价 Cart cart = (Cart)request.getSession().getAttribute("cart"); float total = (float)cart.getTotal(); //账户余额必须大于购物车商品总价 if(balance < total){ session.setAttribute("msg","账户余额不足"); return "user/payFail"; } return "user/pay"; } /** * 添加订单 * @param request * @param phone * @param address * @param redirectAttributes * @return * @throws Exception */ @RequestMapping(value = "addOrder") public String addOrder(HttpServletRequest request,@RequestParam("phone") String phone, @RequestParam("address") String address,RedirectAttributes redirectAttributes)throws Exception{ //session获取购物车 Cart cart = (Cart)request.getSession().getAttribute("cart"); //创建订单对象并设置属性 Orders order = new Orders(); //随机创建5位数字串 order.setOid(Long.parseLong(Uuid.randomNum1(5))); Timestamp d = new Timestamp(System.currentTimeMillis()); order.setOrdertime(d); order.setState(1);//收货状态 1:未付款 2:未收货 3:已收货 order.setTotal((float)cart.getTotal()); User user = (User)request.getSession().getAttribute("user"); order.setUid(user.getUid()); order.setPhone(phone); order.setAddress(address); userService.addOrder(order); //将oid传到pay方法中 redirectAttributes.addAttribute("oid",order.getOid()); //循环遍历cart,用orderItem替换cartItem for(CartItem cartItem : cart.getCartItems()){ OrderItem orderItem = new OrderItem(); orderItem.setCount(cartItem.getCount()); orderItem.setFid(cartItem.getFood().getFid()); orderItem.setSubtotal((float)cartItem.getSubtotal()); orderItem.setOid(order.getOid()); userService.addOrderItem(orderItem); } //清空购物车 cart.clear(); return "redirect:/user/pay"; } /** * 支付功能 * @param oid * @param request * @param session * @param redirectAttributes * @return * @throws Exception */ @RequestMapping(value = "pay") public String pay(@RequestParam("oid") long oid,HttpServletRequest request,HttpSession session, RedirectAttributes redirectAttributes)throws Exception{ Orders order = userService.findOrder(oid); //获取订单总金额 float total = order.getTotal(); //获取session中的用户id User user = (User)session.getAttribute("user"); long uid = user.getUid(); request.setAttribute("order",order); int a = userService.pay(total,uid); if(a <= 0){ return "user/payFail"; } return "user/paySuccess"; } /** * 根据用户id查询订单 * @param uid * @param session * @return * @throws Exception */ @RequestMapping(value = "findOrders") public String findOrders(@RequestParam("uid") long uid,HttpSession session)throws Exception{ List<Orders> listOrders = userService.findOrders(uid); session.setAttribute("listOrders",listOrders); return "user/orders"; } /** * 确认收货 * @param oid * @param session * @return * @throws Exception */ @RequestMapping(value = "over") public String over(@RequestParam("oid") long oid,HttpSession session)throws Exception{ int a = userService.over(oid); if(a <= 0){ return "user/payFail"; } return "redirect:/user/over2"; } /** * 查询用户订单 配合确认收货后页面的更新 * @param session * @return * @throws Exception */ @RequestMapping(value = "over2") public String over2(HttpSession session)throws Exception{ User user = (User)session.getAttribute("user"); long uid = user.getUid(); List<Orders> listOrders = userService.findOrders(uid); session.setAttribute("listOrders",listOrders); return "user/orders"; } /** * 查看订单详情 * @param oid * @param session * @return * @throws Exception */ @RequestMapping(value = "orderDetail") public String orderDetail(@RequestParam("oid") long oid,HttpSession session)throws Exception{ //查找订单并放入sesison中 Orders order = userService.findOrder(oid); session.setAttribute("order",order); //查询订单详情 List<OrderItem> listOrderItem = userService.orderDetail(oid); session.setAttribute("listOrderItem",listOrderItem); List<Food> listFood = new ArrayList<Food>(); //遍历List查找食物id for (OrderItem orderItem : listOrderItem) { long fid = orderItem.getFid(); //根据食物id查找到食物对象 Food food = userService.findFood(fid); //将食物对象添加到List集合中 listFood.add(food); } //将List集合保存到session session.setAttribute("listFood",listFood); return "user/orderItem"; } }
三、页面效果图
1、商家页面
登录地址:http://localhost:8080/admin/logout
(1)登录页面
(2)添加店铺
(3)添加食物
(4)订单管理
查看详情
(5)所有店铺
点击图片查看食物
2、用户页面
地址:http://localhost:8080/
(1)商品页面
点击图片,可以点击添加购物车
(2)我的购物车
点击去支付后,填写电话和收货地址,点击购买
显示支付成功
(3)我的订单
商家显示未收货
查看订单详情
3、源码地址
csdn下载地址:https://download.csdn.net/download/weixin_44385486/87235146
程序员小王博客下载地址:http://wanghj.online/index.php/2022/12/02/ssmjsp实现《吃货联盟外卖系统》/