栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot+MyBatis+MySQL电脑商城项目实战(主要包括用户、商品、商品类别、收藏、订单、购物车、收货地址等模块功能)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot+MyBatis+MySQL电脑商城项目实战(主要包括用户、商品、商品类别、收藏、订单、购物车、收货地址等模块功能)

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录
  • 一、项目目录结构
  • 二、StoreApplication.javapom.xml、application.properties
    • StoreApplication.java
    • pom.xml
    • application.properties
  • 三、interceptor、config、util(工具类返回一串json数据)
    • 1. interceptor
      • Loginlnterceptor.java(拦截器)
    • 2. config
      • LoginlnterceptorConfigurer.java
      • RedisConfig.java(配置redis)
    • 3. util
      • JsonResult.java
  • 四、entity+vo
    • **User.java**
    • **BaseEntity.java**
    • **Address.java**
    • **Product.java**
    • **District.java**
    • **Cart.java**
    • **Order.java**
    • **OrderItem.java**
    • CartVO.java
  • 五、 mapper(接口文件)
    • UserMapper.java
    • AddressMapper.java
    • ProductMapper.java
    • DistrictMapper.java
    • CartMapper.java
    • OrderMapper.java
  • 六、mapper(映射文件)
    • UserMapper.xml
    • AddressMapper.xml
    • DistrictMapper.xml
    • ProductMapper.xml
    • CartMapper.xml
    • OrderMapper.xml
  • 七、service
    • 1. ex(错误抛出)
      • UserNotFoundException.java
      • UsernameDuplicatedException.java
      • UpdateException.java
      • ServiceException.java
      • ProductNotFoundException.java
      • PasswordNotMatchException.java
      • InsertException.java
      • DeleteException.java
      • CartNotFoundException.java
      • AddressNotFoundException.java
      • AddressCountLimitException.java
      • AccessDeniedException.java
    • 2. 接口文件
      • IUserService.java
      • IAddressService.java
      • IDistrictService.java
      • IProductService.java
      • ICartService.java
      • IOrderService.java
    • 3. impl(接口实现类)
      • UserServiceImpl.java
      • AddressServiceImpl.java
      • DistrictServiceImpl.java
      • ProductServiceImpl.java
      • CartServiceImpl.java
      • OrderServiceImpl.java
  • 八、controller
    • ex
      • FileEmptyException.java
      • FileSizeException.java
      • FileStateException.java
      • FileTypeException.java
      • FileUploadException.java
      • FileUploadIOException.java
    • 控制器
      • UserController.java
      • BaseController.java
      • AddressController.java
      • DistrictController.java
      • ProductController.java
      • CartController.java
      • OrderController.java
  • 总结


提示:项目源码https://gitee.com/alfred-tfk/store_-pc

一、项目目录结构

二、StoreApplication.javapom.xml、application.properties StoreApplication.java
package com.lll.store;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
//@MapperScan 指定当前项目中的Mapper接口路径的位置,再项目启动的时候会自动加载所有的接口
@MapperScan("com.lll.store.mapper")
public class StoreApplication {

    public static void main(String[] args) {
        SpringApplication.run(StoreApplication.class, args);
    }

}

pom.xml


    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.6.4
         
    
    com.lll
    store
    0.0.1-SNAPSHOT
    store
    Demo project for Spring Boot
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.2.2
        

        
            mysql
            mysql-connector-java
            runtime
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.projectlombok
            lombok
        
        
            junit
            junit
            test
        
        
            junit
            junit
            test
        
        
            junit
            junit
            test
        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/store?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root

#定义变量在AddressServiceImpl中使用@Value("${user.address.max-count}")
user.address.max-count=20
mybatis.mapper-locations=classpath:mapper
public class Loginlnterceptor implements HandlerInterceptor {

    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // HttpServletResponse对象来获取session对象
        Object obj = request.getSession().getAttribute("uid");
        if (obj == null){
            // 说明用户没有登录过系统,则重定向到login.html页面
            response.sendRedirect("/web/login.html");
            // 结束后续的调用
            return false;
        }
        // 请求放行
        return true;
    }
}

2. config LoginlnterceptorConfigurer.java
package com.lll.store.config;

import com.lll.store.interceptor.Loginlnterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

@Configuration //加载当前的拦截器并进行注册

public class LoginlnterceptorConfigurer implements WebMvcConfigurer {


    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //创建自定义的拦截器对象
        HandlerInterceptor interceptor = new Loginlnterceptor();
        //配置白名单:存放在一个List集合
        List patterns = new ArrayList<>();
        patterns.add("/bootstrap3
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        // 使用JSON格式序列化对象,对缓存数据key和value进行转换
        Jackson2JsonRedisSerializer jsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        // 解决查询缓存转换异常问题
        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,feild,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如string,Integer等会异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jsonRedisSerializer.setObjectMapper(om);
        // 设置RedisTemplate模板API的序列化方式为JSON
        template.setDefaultSerializer(jsonRedisSerializer);
        return template;
    }

    
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory){
        // 分别创建String和JSON格式化序列对象,对缓存数据key和value进行转换
        RedisSerializer stringRedisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        // 解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jsonRedisSerializer.setObjectMapper(om);
        // 定制缓存数据序列化方式及时效
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofDays(7)) //设置缓存有效期为1天
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(stringRedisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jsonRedisSerializer))
                .disableCachingNullValues(); // 对空数据不进行缓存
        RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(config).build();
        return cacheManager;
    }
}
3. util JsonResult.java
package com.lll.store.util;

import lombok.Data;

import java.io.Serializable;


public class JsonResult implements Serializable {
    //状态码
    private Integer state;
    //描述信息
    private String message;
    //数据泛型
    private E data;

    public JsonResult(Integer state) {
        this.state = state;
    }

    public JsonResult(Throwable e) {
        this.message = e.getMessage();
    }

    public JsonResult(Integer state, E data) {
        this.state = state;
        this.data = data;
    }

    public JsonResult() {
    }

    public Integer getState() {
        return state;
    }

    public void setState(Integer state) {
        this.state = state;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public E getData() {
        return data;
    }

    public void setData(E data) {
        this.data = data;
    }
}

四、entity+vo User.java
package com.lll.store.entity;

import lombok.Data;
import org.springframework.stereotype.Component;

import java.io.Serializable;


@Data
public class User extends BaseEntity implements Serializable {
    private Integer uid;
    private String username;
    private String password;
    private String salt;
    private String phone;
    private String email;
    private Integer gender;
    private String avatar;
    private Integer isDelete;

}

BaseEntity.java
package com.lll.store.entity;

import lombok.Data;
import java.io.Serializable;
import java.util.Date;


@Data
public class BaseEntity implements Serializable {
    private String createdUser;
    private Date createdTime;
    private String modifiedUser;
    private Date modifiedTime;


}

Address.java
package com.lll.store.entity;
import java.io.Serializable;


public class Address extends BaseEntity implements Serializable {
    private Integer aid;
    private Integer uid;
    private String name;
    private String provinceName;
    private String provinceCode;
    private String cityName;
    private String cityCode;
    private String areaName;
    private String areaCode;
    private String zip;
    private String address;
    private String phone;
    private String tel;
    private String tag;
    private Integer isDefault;

    public Integer getAid() {
        return aid;
    }

    public void setAid(Integer aid) {
        this.aid = aid;
    }

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getProvinceName() {
        return provinceName;
    }

    public void setProvinceName(String provinceName) {
        this.provinceName = provinceName;
    }

    public String getProvinceCode() {
        return provinceCode;
    }

    public void setProvinceCode(String provinceCode) {
        this.provinceCode = provinceCode;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    public String getCityCode() {
        return cityCode;
    }

    public void setCityCode(String cityCode) {
        this.cityCode = cityCode;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public String getAreaCode() {
        return areaCode;
    }

    public void setAreaCode(String areaCode) {
        this.areaCode = areaCode;
    }

    public String getZip() {
        return zip;
    }

    public void setZip(String zip) {
        this.zip = zip;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getTag() {
        return tag;
    }

    public void setTag(String tag) {
        this.tag = tag;
    }

    public Integer getIsDefault() {
        return isDefault;
    }

    public void setIsDefault(Integer isDefault) {
        this.isDefault = isDefault;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Address)) return false;

        Address address1 = (Address) o;

        if (getAid() != null ? !getAid().equals(address1.getAid()) : address1.getAid() != null) return false;
        if (getUid() != null ? !getUid().equals(address1.getUid()) : address1.getUid() != null) return false;
        if (getName() != null ? !getName().equals(address1.getName()) : address1.getName() != null) return false;
        if (getProvinceName() != null ? !getProvinceName().equals(address1.getProvinceName()) : address1.getProvinceName() != null)
            return false;
        if (getProvinceCode() != null ? !getProvinceCode().equals(address1.getProvinceCode()) : address1.getProvinceCode() != null)
            return false;
        if (getCityName() != null ? !getCityName().equals(address1.getCityName()) : address1.getCityName() != null)
            return false;
        if (getCityCode() != null ? !getCityCode().equals(address1.getCityCode()) : address1.getCityCode() != null)
            return false;
        if (getAreaName() != null ? !getAreaName().equals(address1.getAreaName()) : address1.getAreaName() != null)
            return false;
        if (getAreaCode() != null ? !getAreaCode().equals(address1.getAreaCode()) : address1.getAreaCode() != null)
            return false;
        if (getZip() != null ? !getZip().equals(address1.getZip()) : address1.getZip() != null) return false;
        if (getAddress() != null ? !getAddress().equals(address1.getAddress()) : address1.getAddress() != null)
            return false;
        if (getPhone() != null ? !getPhone().equals(address1.getPhone()) : address1.getPhone() != null) return false;
        if (getTel() != null ? !getTel().equals(address1.getTel()) : address1.getTel() != null) return false;
        if (getTag() != null ? !getTag().equals(address1.getTag()) : address1.getTag() != null) return false;
        return getIsDefault() != null ? getIsDefault().equals(address1.getIsDefault()) : address1.getIsDefault() == null;
    }

    @Override
    public int hashCode() {
        int result = getAid() != null ? getAid().hashCode() : 0;
        result = 31 * result + (getUid() != null ? getUid().hashCode() : 0);
        result = 31 * result + (getName() != null ? getName().hashCode() : 0);
        result = 31 * result + (getProvinceName() != null ? getProvinceName().hashCode() : 0);
        result = 31 * result + (getProvinceCode() != null ? getProvinceCode().hashCode() : 0);
        result = 31 * result + (getCityName() != null ? getCityName().hashCode() : 0);
        result = 31 * result + (getCityCode() != null ? getCityCode().hashCode() : 0);
        result = 31 * result + (getAreaName() != null ? getAreaName().hashCode() : 0);
        result = 31 * result + (getAreaCode() != null ? getAreaCode().hashCode() : 0);
        result = 31 * result + (getZip() != null ? getZip().hashCode() : 0);
        result = 31 * result + (getAddress() != null ? getAddress().hashCode() : 0);
        result = 31 * result + (getPhone() != null ? getPhone().hashCode() : 0);
        result = 31 * result + (getTel() != null ? getTel().hashCode() : 0);
        result = 31 * result + (getTag() != null ? getTag().hashCode() : 0);
        result = 31 * result + (getIsDefault() != null ? getIsDefault().hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "Address{" +
                "aid=" + aid +
                ", uid=" + uid +
                ", name='" + name + ''' +
                ", provinceName='" + provinceName + ''' +
                ", provinceCode='" + provinceCode + ''' +
                ", cityName='" + cityName + ''' +
                ", cityCode='" + cityCode + ''' +
                ", areaName='" + areaName + ''' +
                ", areaCode='" + areaCode + ''' +
                ", zip='" + zip + ''' +
                ", address='" + address + ''' +
                ", phone='" + phone + ''' +
                ", tel='" + tel + ''' +
                ", tag='" + tag + ''' +
                ", isDefault=" + isDefault +
                "} " + super.toString();
    }
}

Product.java
package com.lll.store.entity;

import java.io.Serializable;


public class Product extends BaseEntity implements Serializable {
    private Integer id;
    private Integer categoryId;
    private String itemType;
    private String title;
    private String sellPoint;
    private Long price;
    private Integer num;
    private String image;
    private Integer status;
    private Integer priority;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(Integer categoryId) {
        this.categoryId = categoryId;
    }

    public String getItemType() {
        return itemType;
    }

    public void setItemType(String itemType) {
        this.itemType = itemType;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSellPoint() {
        return sellPoint;
    }

    public void setSellPoint(String sellPoint) {
        this.sellPoint = sellPoint;
    }

    public Long getPrice() {
        return price;
    }

    public void setPrice(Long price) {
        this.price = price;
    }

    public Integer getNum() {
        return num;
    }

    public void setNum(Integer num) {
        this.num = num;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public Integer getPriority() {
        return priority;
    }

    public void setPriority(Integer priority) {
        this.priority = priority;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Product)) return false;

        Product product = (Product) o;

        if (getId() != null ? !getId().equals(product.getId()) : product.getId() != null) return false;
        if (getCategoryId() != null ? !getCategoryId().equals(product.getCategoryId()) : product.getCategoryId() != null)
            return false;
        if (getItemType() != null ? !getItemType().equals(product.getItemType()) : product.getItemType() != null)
            return false;
        if (getTitle() != null ? !getTitle().equals(product.getTitle()) : product.getTitle() != null) return false;
        if (getSellPoint() != null ? !getSellPoint().equals(product.getSellPoint()) : product.getSellPoint() != null)
            return false;
        if (getPrice() != null ? !getPrice().equals(product.getPrice()) : product.getPrice() != null) return false;
        if (getNum() != null ? !getNum().equals(product.getNum()) : product.getNum() != null) return false;
        if (getImage() != null ? !getImage().equals(product.getImage()) : product.getImage() != null) return false;
        if (getStatus() != null ? !getStatus().equals(product.getStatus()) : product.getStatus() != null) return false;
        return getPriority() != null ? getPriority().equals(product.getPriority()) : product.getPriority() == null;
    }

    @Override
    public int hashCode() {
        int result = getId() != null ? getId().hashCode() : 0;
        result = 31 * result + (getCategoryId() != null ? getCategoryId().hashCode() : 0);
        result = 31 * result + (getItemType() != null ? getItemType().hashCode() : 0);
        result = 31 * result + (getTitle() != null ? getTitle().hashCode() : 0);
        result = 31 * result + (getSellPoint() != null ? getSellPoint().hashCode() : 0);
        result = 31 * result + (getPrice() != null ? getPrice().hashCode() : 0);
        result = 31 * result + (getNum() != null ? getNum().hashCode() : 0);
        result = 31 * result + (getImage() != null ? getImage().hashCode() : 0);
        result = 31 * result + (getStatus() != null ? getStatus().hashCode() : 0);
        result = 31 * result + (getPriority() != null ? getPriority().hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", categoryId=" + categoryId +
                ", itemType='" + itemType + ''' +
                ", title='" + title + ''' +
                ", sellPoint='" + sellPoint + ''' +
                ", price=" + price +
                ", num=" + num +
                ", image='" + image + ''' +
                ", status=" + status +
                ", priority=" + priority +
                "} " + super.toString();
    }
}

District.java
package com.lll.store.entity;

import java.io.Serializable;


public class District implements Serializable {
    private Integer id;
    private String parent;
    private String code;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getParent() {
        return parent;
    }

    public void setParent(String parent) {
        this.parent = parent;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof District)) return false;

        District district = (District) o;

        if (getId() != null ? !getId().equals(district.getId()) : district.getId() != null) return false;
        if (getParent() != null ? !getParent().equals(district.getParent()) : district.getParent() != null)
            return false;
        if (getCode() != null ? !getCode().equals(district.getCode()) : district.getCode() != null) return false;
        return getName() != null ? getName().equals(district.getName()) : district.getName() == null;
    }

    @Override
    public int hashCode() {
        int result = getId() != null ? getId().hashCode() : 0;
        result = 31 * result + (getParent() != null ? getParent().hashCode() : 0);
        result = 31 * result + (getCode() != null ? getCode().hashCode() : 0);
        result = 31 * result + (getName() != null ? getName().hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "District{" +
                "id=" + id +
                ", parent='" + parent + ''' +
                ", code='" + code + ''' +
                ", name='" + name + ''' +
                '}';
    }
}

Cart.java
package com.lll.store.entity;

import java.io.Serializable;


public class Cart extends BaseEntity implements Serializable {
    private Integer cid;
    private Integer uid;
    private Integer pid;
    private Long price;
    private Integer num;

    public Integer getCid() {
        return cid;
    }

    public void setCid(Integer cid) {
        this.cid = cid;
    }

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public Integer getPid() {
        return pid;
    }

    public void setPid(Integer pid) {
        this.pid = pid;
    }

    public Long getPrice() {
        return price;
    }

    public void setPrice(Long price) {
        this.price = price;
    }

    public Integer getNum() {
        return num;
    }

    public void setNum(Integer num) {
        this.num = num;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Cart)) return false;

        Cart cart = (Cart) o;

        if (getCid() != null ? !getCid().equals(cart.getCid()) : cart.getCid() != null) return false;
        if (getUid() != null ? !getUid().equals(cart.getUid()) : cart.getUid() != null) return false;
        if (getPid() != null ? !getPid().equals(cart.getPid()) : cart.getPid() != null) return false;
        if (getPrice() != null ? !getPrice().equals(cart.getPrice()) : cart.getPrice() != null) return false;
        return getNum() != null ? getNum().equals(cart.getNum()) : cart.getNum() == null;
    }

    @Override
    public int hashCode() {
        int result = getCid() != null ? getCid().hashCode() : 0;
        result = 31 * result + (getUid() != null ? getUid().hashCode() : 0);
        result = 31 * result + (getPid() != null ? getPid().hashCode() : 0);
        result = 31 * result + (getPrice() != null ? getPrice().hashCode() : 0);
        result = 31 * result + (getNum() != null ? getNum().hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "Cart{" +
                "cid=" + cid +
                ", uid=" + uid +
                ", pid=" + pid +
                ", price=" + price +
                ", num=" + num +
                "} " + super.toString();
    }
}

Order.java
package com.lll.store.entity;

import java.io.Serializable;
import java.util.Date;


public class Order extends BaseEntity implements Serializable {
    private Integer oid;
    private Integer uid;
    private String recvName;
    private String recvPhone;
    private String recvProvince;
    private String recvCity;
    private String recvArea;
    private String recvAddress;
    private Long totalPrice;
    private Integer status;
    private Date orderTime;
    private Date payTime;

    public Integer getOid() {
        return oid;
    }

    public void setOid(Integer oid) {
        this.oid = oid;
    }

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public String getRecvName() {
        return recvName;
    }

    public void setRecvName(String recvName) {
        this.recvName = recvName;
    }

    public String getRecvPhone() {
        return recvPhone;
    }

    public void setRecvPhone(String recvPhone) {
        this.recvPhone = recvPhone;
    }

    public String getRecvProvince() {
        return recvProvince;
    }

    public void setRecvProvince(String recvProvince) {
        this.recvProvince = recvProvince;
    }

    public String getRecvCity() {
        return recvCity;
    }

    public void setRecvCity(String recvCity) {
        this.recvCity = recvCity;
    }

    public String getRecvArea() {
        return recvArea;
    }

    public void setRecvArea(String recvArea) {
        this.recvArea = recvArea;
    }

    public String getRecvAddress() {
        return recvAddress;
    }

    public void setRecvAddress(String recvAddress) {
        this.recvAddress = recvAddress;
    }

    public Long getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(Long totalPrice) {
        this.totalPrice = totalPrice;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public Date getOrderTime() {
        return orderTime;
    }

    public void setOrderTime(Date orderTime) {
        this.orderTime = orderTime;
    }

    public Date getPayTime() {
        return payTime;
    }

    public void setPayTime(Date payTime) {
        this.payTime = payTime;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Order)) return false;

        Order order = (Order) o;

        if (getOid() != null ? !getOid().equals(order.getOid()) : order.getOid() != null) return false;
        if (getUid() != null ? !getUid().equals(order.getUid()) : order.getUid() != null) return false;
        if (getRecvName() != null ? !getRecvName().equals(order.getRecvName()) : order.getRecvName() != null)
            return false;
        if (getRecvPhone() != null ? !getRecvPhone().equals(order.getRecvPhone()) : order.getRecvPhone() != null)
            return false;
        if (getRecvProvince() != null ? !getRecvProvince().equals(order.getRecvProvince()) : order.getRecvProvince() != null)
            return false;
        if (getRecvCity() != null ? !getRecvCity().equals(order.getRecvCity()) : order.getRecvCity() != null)
            return false;
        if (getRecvArea() != null ? !getRecvArea().equals(order.getRecvArea()) : order.getRecvArea() != null)
            return false;
        if (getRecvAddress() != null ? !getRecvAddress().equals(order.getRecvAddress()) : order.getRecvAddress() != null)
            return false;
        if (getTotalPrice() != null ? !getTotalPrice().equals(order.getTotalPrice()) : order.getTotalPrice() != null)
            return false;
        if (getStatus() != null ? !getStatus().equals(order.getStatus()) : order.getStatus() != null) return false;
        if (getOrderTime() != null ? !getOrderTime().equals(order.getOrderTime()) : order.getOrderTime() != null)
            return false;
        return getPayTime() != null ? getPayTime().equals(order.getPayTime()) : order.getPayTime() == null;
    }

    @Override
    public int hashCode() {
        int result = getOid() != null ? getOid().hashCode() : 0;
        result = 31 * result + (getUid() != null ? getUid().hashCode() : 0);
        result = 31 * result + (getRecvName() != null ? getRecvName().hashCode() : 0);
        result = 31 * result + (getRecvPhone() != null ? getRecvPhone().hashCode() : 0);
        result = 31 * result + (getRecvProvince() != null ? getRecvProvince().hashCode() : 0);
        result = 31 * result + (getRecvCity() != null ? getRecvCity().hashCode() : 0);
        result = 31 * result + (getRecvArea() != null ? getRecvArea().hashCode() : 0);
        result = 31 * result + (getRecvAddress() != null ? getRecvAddress().hashCode() : 0);
        result = 31 * result + (getTotalPrice() != null ? getTotalPrice().hashCode() : 0);
        result = 31 * result + (getStatus() != null ? getStatus().hashCode() : 0);
        result = 31 * result + (getOrderTime() != null ? getOrderTime().hashCode() : 0);
        result = 31 * result + (getPayTime() != null ? getPayTime().hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "Order{" +
                "oid=" + oid +
                ", uid=" + uid +
                ", recvName='" + recvName + ''' +
                ", recvPhone='" + recvPhone + ''' +
                ", recvProvince='" + recvProvince + ''' +
                ", recvCity='" + recvCity + ''' +
                ", recvArea='" + recvArea + ''' +
                ", recvAddress='" + recvAddress + ''' +
                ", totalPrice=" + totalPrice +
                ", status=" + status +
                ", orderTime=" + orderTime +
                ", payTime=" + payTime +
                "} " + super.toString();
    }
}

OrderItem.java
package com.lll.store.entity;

import java.io.Serializable;


public class OrderItem extends BaseEntity implements Serializable {
    private Integer id;
    private Integer oid;
    private Integer pid;
    private String title;
    private String image;
    private Long price;
    private Integer num;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getOid() {
        return oid;
    }

    public void setOid(Integer oid) {
        this.oid = oid;
    }

    public Integer getPid() {
        return pid;
    }

    public void setPid(Integer pid) {
        this.pid = pid;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public Long getPrice() {
        return price;
    }

    public void setPrice(Long price) {
        this.price = price;
    }

    public Integer getNum() {
        return num;
    }

    public void setNum(Integer num) {
        this.num = num;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof OrderItem)) return false;

        OrderItem orderItem = (OrderItem) o;

        if (getId() != null ? !getId().equals(orderItem.getId()) : orderItem.getId() != null) return false;
        if (getOid() != null ? !getOid().equals(orderItem.getOid()) : orderItem.getOid() != null) return false;
        if (getPid() != null ? !getPid().equals(orderItem.getPid()) : orderItem.getPid() != null) return false;
        if (getTitle() != null ? !getTitle().equals(orderItem.getTitle()) : orderItem.getTitle() != null) return false;
        if (getImage() != null ? !getImage().equals(orderItem.getImage()) : orderItem.getImage() != null) return false;
        if (getPrice() != null ? !getPrice().equals(orderItem.getPrice()) : orderItem.getPrice() != null) return false;
        return getNum() != null ? getNum().equals(orderItem.getNum()) : orderItem.getNum() == null;
    }

    @Override
    public int hashCode() {
        int result = getId() != null ? getId().hashCode() : 0;
        result = 31 * result + (getOid() != null ? getOid().hashCode() : 0);
        result = 31 * result + (getPid() != null ? getPid().hashCode() : 0);
        result = 31 * result + (getTitle() != null ? getTitle().hashCode() : 0);
        result = 31 * result + (getImage() != null ? getImage().hashCode() : 0);
        result = 31 * result + (getPrice() != null ? getPrice().hashCode() : 0);
        result = 31 * result + (getNum() != null ? getNum().hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "OrderItem{" +
                "id=" + id +
                ", oid=" + oid +
                ", pid=" + pid +
                ", title='" + title + ''' +
                ", image='" + image + ''' +
                ", price=" + price +
                ", num=" + num +
                "} " + super.toString();
    }
}

CartVO.java
package com.lll.store.vo;

import java.io.Serializable;


public class CartVO implements Serializable {
    private Integer cid;
    private Integer uid;
    private Integer pid;
    private Long price;
    private Integer num;
    private String title;
    private Long realPrice;
    private String image;

    public Integer getCid() {
        return cid;
    }

    public void setCid(Integer cid) {
        this.cid = cid;
    }

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public Integer getPid() {
        return pid;
    }

    public void setPid(Integer pid) {
        this.pid = pid;
    }

    public Long getPrice() {
        return price;
    }

    public void setPrice(Long price) {
        this.price = price;
    }

    public Integer getNum() {
        return num;
    }

    public void setNum(Integer num) {
        this.num = num;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Long getRealPrice() {
        return realPrice;
    }

    public void setRealPrice(Long realPrice) {
        this.realPrice = realPrice;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof CartVO)) return false;

        CartVO cartVO = (CartVO) o;

        if (getCid() != null ? !getCid().equals(cartVO.getCid()) : cartVO.getCid() != null) return false;
        if (getUid() != null ? !getUid().equals(cartVO.getUid()) : cartVO.getUid() != null) return false;
        if (getPid() != null ? !getPid().equals(cartVO.getPid()) : cartVO.getPid() != null) return false;
        if (getPrice() != null ? !getPrice().equals(cartVO.getPrice()) : cartVO.getPrice() != null) return false;
        if (getNum() != null ? !getNum().equals(cartVO.getNum()) : cartVO.getNum() != null) return false;
        if (getTitle() != null ? !getTitle().equals(cartVO.getTitle()) : cartVO.getTitle() != null) return false;
        if (getRealPrice() != null ? !getRealPrice().equals(cartVO.getRealPrice()) : cartVO.getRealPrice() != null)
            return false;
        return getImage() != null ? getImage().equals(cartVO.getImage()) : cartVO.getImage() == null;
    }

    @Override
    public int hashCode() {
        int result = getCid() != null ? getCid().hashCode() : 0;
        result = 31 * result + (getUid() != null ? getUid().hashCode() : 0);
        result = 31 * result + (getPid() != null ? getPid().hashCode() : 0);
        result = 31 * result + (getPrice() != null ? getPrice().hashCode() : 0);
        result = 31 * result + (getNum() != null ? getNum().hashCode() : 0);
        result = 31 * result + (getTitle() != null ? getTitle().hashCode() : 0);
        result = 31 * result + (getRealPrice() != null ? getRealPrice().hashCode() : 0);
        result = 31 * result + (getImage() != null ? getImage().hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "CartVO{" +
                "cid=" + cid +
                ", uid=" + uid +
                ", pid=" + pid +
                ", price=" + price +
                ", num=" + num +
                ", title='" + title + ''' +
                ", realPrice=" + realPrice +
                ", image='" + image + ''' +
                '}';
    }
}

五、 mapper(接口文件) UserMapper.java
package com.lll.store.mapper;

import com.lll.store.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.util.Date;


public interface UserMapper {
    
    Integer insert(User user);

    
    User findByUsername(String username);

    
    Integer updatePasswordByUid(Integer uid, String password, String modifiedUser, Date modifiedTime);

    
    User findByUid(Integer uid);

    
    Integer updateInfoByUid(User user);

    
    Integer updateAvatarByUid(
            @Param("uid") Integer uid,
            @Param("avatar") String avatar,
            @Param("modifiedUser") String modifiedUser,
            @Param("modifiedTime") Date modifiedTime
    );
}

AddressMapper.java
package com.lll.store.mapper;

import com.lll.store.entity.Address;
import org.apache.ibatis.annotations.Param;

import java.util.Date;
import java.util.List;


public interface AddressMapper {
    
    Integer insert(Address address);

    
    Integer countByUid(Integer uid);

    
    List
findByUid(Integer uid); Address findByAid(Integer aid); Integer updateNonDefaultByUid(Integer uid); Integer updateDefaultByAid( @Param("aid") Integer aid, @Param("modifiedUser") String modifiedUser, @Param("modifiedTime") Date modifiedTime); Integer deleteByAid(Integer aid); Address findLastModified(Integer uid); }
ProductMapper.java
package com.lll.store.mapper;

import com.lll.store.entity.Product;

import java.util.List;


public interface ProductMapper {
    
    List findHotList();

    
    Product findById(Integer id);
}

DistrictMapper.java
package com.lll.store.mapper;

import com.lll.store.entity.District;

import java.util.List;


public interface DistrictMapper {
    
    List findByParent(String parent);

    
    String findNameByCode(String code);
}

CartMapper.java
package com.lll.store.mapper;

import com.lll.store.entity.Cart;
import com.lll.store.vo.CartVO;
import org.apache.ibatis.annotations.Param;

import java.util.Date;
import java.util.List;


public interface CartMapper {
    
    Integer insert(Cart cart);

    
    Integer updateNumByCid(
            @Param("cid") Integer cid,
            @Param("num") Integer num,
            @Param("modifiedUser") String modifiedUser,
            @Param("modifiedTime") Date modifiedTime);

    
    Cart findByUidAndPid(
            @Param("uid") Integer uid,
            @Param("pid") Integer pid);

    
    List findVOByUid(Integer uid);

    
    Cart findByCid(Integer cid);

    
    List findVOByCids(Integer[] cids);
}

OrderMapper.java
package com.lll.store.mapper;

import com.lll.store.entity.Order;
import com.lll.store.entity.OrderItem;


public interface OrderMapper {
    
    Integer insertOrder(Order order);

    
    Integer insertOrderItem(OrderItem orderItem);
}

六、mapper(映射文件) UserMapper.xml




    
    
    
        
        
        
        
        
        
        
        
        

    

    
    
    
    
        INSERT INTO t_user(
        username,password,
        salt,phone,
        email,gender,
        avatar,is_delete,
        created_user,created_time,
        modified_user,modified_time
        ) VALUES (
        #{username},#{password},
        #{salt},#{phone},
        #{email},#{gender},
        #{avatar},#{isDelete},
        #{createdUser},#{createdTime},
        #{modifiedUser},#{modifiedTime}
        )
        
    

    
    
    
        SELECT * from t_user WHERe uid=#{uid}
    

    
        UPDATE t_user SET
        
        phone = #{phone},
        email = #{email},
        gender = #{gender},
        modified_user = #{modifiedUser},
        modified_time = #{modifiedTime}
        WHERe uid = #{uid}
    

    
        UPDATE t_user SET
            avatar = #{avatar},
            modified_user = #{modifiedUser},
            modified_time = #{modifiedTime}
        WHERe
            uid = #{uid}
    

AddressMapper.xml




    
        
        
        
        
        
        
        
        
        
        
        
        
    

    
    
        INSERT INTO t_address (
            uid, name, province_name, province_code, city_name, city_code, area_name, area_code, zip,
            address, phone, tel, tag, is_default, created_user, created_time, modified_user, modified_time
        ) VALUES (
            #{uid}, #{name}, #{provinceName}, #{provinceCode}, #{cityName}, #{cityCode}, #{areaName},
            #{areaCode}, #{zip}, #{address}, #{phone}, #{tel}, #{tag}, #{isDefault}, #{createdUser},
            #{createdTime}, #{modifiedUser}, #{modifiedTime}
        )
    

    
    
        SELECT
            *
        FROM
            t_address
        WHERe
            uid=#{uid}
        ORDER BY
            is_default DESC, created_time DESC
    

    
    
        UPDATE
            t_address
        SET
            is_default=0
        WHERe
            uid=#{uid}
    

    
    
        UPDATE
            t_address
        SET
            is_default=1,
            modified_user=#{modifiedUser},
            modified_time=#{modifiedTime}
        WHERe
            aid=#{aid}
    

    
    
        SELECT
            *
        FROM
            t_address
        WHERe
            uid=#{uid}
        ORDER BY
            modified_time DESC
            LIMIT 0,1
    

DistrictMapper.xml



    
    
        SELECT
            name
        FROM
            t_dict_district
        WHERe
            code=#{code}
    

ProductMapper.xml



    
        
        
        
        
        
        
        
        
    

    
    
        SELECT
            *
        FROM
            t_product
        WHERe
            id=#{id}
    

CartMapper.xml



    
        
        
        
        
        
    

    
    
        INSERT INTO t_cart (uid, pid, price, num, created_user, created_time, modified_user, modified_time)
        VALUES (#{uid}, #{pid}, #{price}, #{num}, #{createdUser}, #{createdTime}, #{modifiedUser}, #{modifiedTime})
    

    
    
        UPDATE
            t_cart
        SET
            num=#{num},
            modified_user=#{modifiedUser},
            modified_time=#{modifiedTime}
        WHERe
            cid=#{cid}
    

    
    
        SELECT
            cid,
            uid,
            pid,
            t_cart.price,
            t_cart.num,
            t_product.title,
            t_product.price AS realPrice,
            t_product.image
        FROM
            t_cart
                LEFT JOIN t_product ON t_cart.pid = t_product.id
        WHERe
            uid = #{uid}
        ORDER BY
            t_cart.created_time DESC
    

    
    
        SELECT
            cid,
            uid,
            pid,
            t_cart.price,
            t_cart.num,
            t_product.title,
            t_product.price AS realPrice,
            t_product.image
        FROM
            t_cart
                LEFT JOIN t_product ON t_cart.pid = t_product.id
        WHERe
            cid IN (
                
                    #{cid}
                
            )
        ORDER BY
            t_cart.created_time DESC
    

OrderMapper.xml



    
    
        INSERT INTO t_order (
            uid, recv_name, recv_phone, recv_province, recv_city, recv_area, recv_address,
            total_price,status, order_time, pay_time, created_user, created_time, modified_user,
            modified_time
        ) VALUES (
            #{uid}, #{recvName}, #{recvPhone}, #{recvProvince}, #{recvCity}, #{recvArea},
            #{recvAddress}, #{totalPrice}, #{status}, #{orderTime}, #{payTime}, #{createdUser},
            #{createdTime}, #{modifiedUser}, #{modifiedTime}
        )
    

    
    
        INSERT INTO t_order_item (
            oid, pid, title, image, price, num, created_user,
            created_time, modified_user, modified_time
        ) VALUES (
            #{oid}, #{pid}, #{title}, #{image}, #{price}, #{num}, #{createdUser},
            #{createdTime}, #{modifiedUser}, #{modifiedTime}
        )
    

七、service 1. ex(错误抛出) UserNotFoundException.java
package com.lll.store.service.ex;


public class UserNotFoundException extends ServiceException {
    public UserNotFoundException() {
        super();
    }

    public UserNotFoundException(String message) {
        super(message);
    }

    public UserNotFoundException(String message, Throwable cause) {
        super(message, cause);
    }

    public UserNotFoundException(Throwable cause) {
        super(cause);
    }

    protected UserNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

UsernameDuplicatedException.java
package com.lll.store.service.ex;


public class UsernameDuplicatedException extends ServiceException{
    public UsernameDuplicatedException() {
    }

    public UsernameDuplicatedException(String message) {
        super(message);
    }

    public UsernameDuplicatedException(String message, Throwable cause) {
        super(message, cause);
    }

    public UsernameDuplicatedException(Throwable cause) {
        super(cause);
    }

    public UsernameDuplicatedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

UpdateException.java
package com.lll.store.service.ex;

import org.springframework.context.annotation.Configuration;


public class UpdateException extends ServiceException{
    public UpdateException() {
        super();
    }

    public UpdateException(String message) {
        super(message);
    }

    public UpdateException(String message, Throwable cause) {
        super(message, cause);
    }

    public UpdateException(Throwable cause) {
        super(cause);
    }

    public UpdateException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

ServiceException.java
package com.lll.store.service.ex;


public class ServiceException extends RuntimeException {
    public ServiceException() {
        super();
    }

    public ServiceException(String message) {
        super(message);
    }

    public ServiceException(String message, Throwable cause) {
        super(message, cause);
    }

    public ServiceException(Throwable cause) {
        super(cause);
    }

    public ServiceException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

ProductNotFoundException.java
package com.lll.store.service.ex;


public class ProductNotFoundException extends ServiceException {
    public ProductNotFoundException() {
        super();
    }

    public ProductNotFoundException(String message) {
        super(message);
    }

    public ProductNotFoundException(String message, Throwable cause) {
        super(message, cause);
    }

    public ProductNotFoundException(Throwable cause) {
        super(cause);
    }

    protected ProductNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

PasswordNotMatchException.java
package com.lll.store.service.ex;


public class PasswordNotMatchException extends ServiceException {
    public PasswordNotMatchException() {
        super();
    }

    public PasswordNotMatchException(String message) {
        super(message);
    }

    public PasswordNotMatchException(String message, Throwable cause) {
        super(message, cause);
    }

    public PasswordNotMatchException(Throwable cause) {
        super(cause);
    }

    protected PasswordNotMatchException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

InsertException.java
package com.lll.store.service.ex;


public class InsertException extends ServiceException{
    public InsertException() {
    }

    public InsertException(String message) {
        super(message);
    }

    public InsertException(String message, Throwable cause) {
        super(message, cause);
    }

    public InsertException(Throwable cause) {
        super(cause);
    }

    public InsertException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

DeleteException.java
package com.lll.store.service.ex;


public class DeleteException extends ServiceException {
    public DeleteException() {
        super();
    }

    public DeleteException(String message) {
        super(message);
    }

    public DeleteException(String message, Throwable cause) {
        super(message, cause);
    }

    public DeleteException(Throwable cause) {
        super(cause);
    }

    protected DeleteException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

CartNotFoundException.java
package com.lll.store.service.ex;


public class CartNotFoundException extends ServiceException {
    public CartNotFoundException() {
        super();
    }

    public CartNotFoundException(String message) {
        super(message);
    }

    public CartNotFoundException(String message, Throwable cause) {
        super(message, cause);
    }

    public CartNotFoundException(Throwable cause) {
        super(cause);
    }

    protected CartNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

AddressNotFoundException.java
package com.lll.store.service.ex;


public class AddressNotFoundException extends ServiceException {
    public AddressNotFoundException() {
        super();
    }

    public AddressNotFoundException(String message) {
        super(message);
    }

    public AddressNotFoundException(String message, Throwable cause) {
        super(message, cause);
    }

    public AddressNotFoundException(Throwable cause) {
        super(cause);
    }

    protected AddressNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

AddressCountLimitException.java
package com.lll.store.service.ex;


public class AddressCountLimitException extends ServiceException {
    public AddressCountLimitException() {
        super();
    }

    public AddressCountLimitException(String message) {
        super(message);
    }

    public AddressCountLimitException(String message, Throwable cause) {
        super(message, cause);
    }

    public AddressCountLimitException(Throwable cause) {
        super(cause);
    }

    protected AddressCountLimitException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

AccessDeniedException.java
package com.lll.store.service.ex;


public class AccessDeniedException extends ServiceException {
    public AccessDeniedException() {
        super();
    }

    public AccessDeniedException(String message) {
        super(message);
    }

    public AccessDeniedException(String message, Throwable cause) {
        super(message, cause);
    }

    public AccessDeniedException(Throwable cause) {
        super(cause);
    }

    protected AccessDeniedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

2. 接口文件 IUserService.java
package com.lll.store.service;

import com.lll.store.entity.User;
import org.apache.ibatis.annotations.Param;

import java.util.Date;


public interface IUserService {
    
    void reg(User user);

    
    User login(String username, String password);

    void changePassword(Integer uid, String username, String oldPassword, String newPassword);

    
    User getByUid(Integer uid);

    
    void changeInfo(Integer uid, String username, User user);

    
    void changeAvatar(Integer uid, String avatar, String username);
}

IAddressService.java
package com.lll.store.service;

import com.lll.store.entity.Address;

import java.util.List;


public interface IAddressService {
    
    void addNewAddress(Integer uid, String username, Address address);

    List
getByUid(Integer uid); void setDefault(Integer aid, Integer uid, String username); void delete(Integer aid, Integer uid, String username); Address getByAid(Integer aid, Integer uid); }
IDistrictService.java
package com.lll.store.service;

import com.lll.store.entity.District;

import java.util.List;


public interface IDistrictService {
    
    List getByParent(String parent);

    
    String getNameByCode(String code);
}

IProductService.java
package com.lll.store.service;

import com.lll.store.entity.Product;

import java.util.List;


public interface IProductService {
    
    List findHotList();

    
    Product findById(Integer id);
}

ICartService.java
package com.lll.store.service;

import com.lll.store.vo.CartVO;

import java.util.List;


public interface ICartService {
    
    void addToCart(Integer uid, Integer pid, Integer amount, String username);

    
    List getVOByUid(Integer uid);

    
    Integer addNum(Integer cid, Integer uid, String username);

    
    List getVOByCids(Integer uid, Integer[] cids);
}

IOrderService.java
package com.lll.store.service;

import com.lll.store.entity.Order;


public interface IOrderService {
    
    Order create(Integer aid, Integer[] cids, Integer uid, String username);
}

3. impl(接口实现类) UserServiceImpl.java
package com.lll.store.service.impl;

import com.lll.store.entity.User;
import com.lll.store.mapper.UserMapper;
import com.lll.store.service.IUserService;
import com.lll.store.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.file.attribute.UserPrincipalNotFoundException;
import java.util.Date;
import java.util.UUID;


@Service //@Server注解:将当前的对象交给Spring来管理,自动创建对象以及对象的维护
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void reg(User user) {
        // 通过user参数来获取传递过来的username
        String username = user.getUsername();
        // 调用findByUsername(username)判断用户是否被注册过
        User result = userMapper.findByUsername(username);
        // 判断结果集是否为null则抛出用户名被占用的异常
        if (result != null) {
            //抛出异常
            throw new UsernameDuplicatedException("用户名被占用");
        }

        //密码加密处理的实现:md5算法的形式
        //串+password+串---md5算法进行加密,连续加载三次
        //盐值 +password+盐值---盐值就是一个随机的字符串
        String oldPassword = user.getPassword();
        //获取盐值(随即生成一个盐值)全大写
        String salt = UUID.randomUUID().toString().toUpperCase();
        //将密码和盐值作为一个整体进行加密处理,忽略原有密码的强度提升了数据的安全性
        String md5Password = getMD5Password(oldPassword, salt);
        //将加密之后的密码重新补全设置到user对象中
        user.setPassword(md5Password);
//        System.out.println(user.getPassword());
        //将盐值补全到user中
        user.setSalt(salt);
        //补全数据:is_delete设置成0
        user.setIsDelete(0);
        //补全数据:4个日志字段信息
        user.setCreatedUser(user.getUsername());
        user.setModifiedUser(user.getUsername());
        Date date = new Date();
        user.setCreatedTime(date);
        user.setModifiedTime(date);

        //执行注册业务功能的实现(rows==1)
        Integer rows = userMapper.insert(user);
        if (rows != 1) {
            throw new InsertException("在用户注册过程中产生了未知的异常");
        }

    }

    @Override
    public User login(String username, String password) {
        //根据用户名称来查询用户的数据是否存在,如果不在则抛出异常
        User result = userMapper.findByUsername(username);
        if (result == null) {
            throw new UserNotFoundException("用户数据不存在");
        }
        //检测用户的密码是否匹配
        //1.先获取到数据库中的加密之后的密码
        String oldPassword = result.getPassword();
        //2.和用户的传递过来的密码进行比较
        //2.1 先获取盐值:上一次注册时所自动生成的盐值
        String salt = result.getSalt();
        //2.2 将用户的密码按照相同的md5算法的规则进行加密
        String newMd5Password = getMD5Password(password, salt);
        //3. 将密码进行比较
        if (!newMd5Password.equals(oldPassword)) {
            throw new PasswordNotMatchException("用户密码错误");
        }

        //判断is_delete字段的值是否为1表示标记为删除
        if (result.getIsDelete() == 1) {
            throw new UserNotFoundException("用户数据不存在");
        }
        //调用mapper层的findByUsername来查询用户的数据,提升系统的性能
        User user = new User();
        user.setUid(result.getUid());
        user.setUsername(result.getUsername());
        // 返回有用户的头像
        user.setAvatar(result.getAvatar());


        // 在Redis缓存中存储,下面一行注释取消掉redis就可以正常使用
//        redisTemplate.opsForValue().set("user_" + user.getUid(), user);

        // 将当前的用户数据返回,返回的数据是为了辅助其他页面做数据展示使用(uid,username,avatar)
        return user;
    }

    @Override
    public void changePassword(Integer uid, String username, String oldPassword, String newPassword) {
        User result = userMapper.findByUid(uid);
        if (result == null || result.getIsDelete() == 1) {
            throw new UserNotFoundException("用户数据不存在");
        }
        // 原始密码和数据库中的密码进行比较
        String oldMd5Password = getMD5Password(oldPassword, result.getSalt());
        if (!result.getPassword().equals(oldMd5Password)) {
            throw new PasswordNotMatchException("密码错误");
        }
        //将新的密码设置到数据库中,将新的密码进行加密再去更新
        String newMd5Password = getMD5Password(newPassword, result.getSalt());
        Integer rows = userMapper.updatePasswordByUid(uid, newMd5Password, username, new Date());
        if (rows != 1) {
            throw new UpdateException("跟新数据产生未知的异常");
        }
    }

    @Override
    public User getByUid(Integer uid) {
        User result = userMapper.findByUid(uid);
        if (result == null || result.getIsDelete() == 1) {
            throw new UserNotFoundException("用户数据不存在");
        }
        User user = new User();
        user.setUsername(result.getUsername());
        user.setPhone(result.getPhone());
        user.setEmail(result.getEmail());
        user.setGender(result.getGender());
        return user;
    }

    
    @Override
    public void changeInfo(Integer uid, String username, User user) {
        User result = userMapper.findByUid(uid);
        if (result == null || result.getIsDelete() == 1) {
            throw new UserNotFoundException("用户数据不存在");
        }

        // 向参数user中补全数据:uid
        user.setUid(uid);
        // 向参数user中补全数据:modifiedUser(username)
        user.setModifiedUser(username);
        // 向参数user中补全数据:modifiedTime(new Date())
        user.setModifiedTime(new Date());
//        user.setEmail();
//        user.setPhone();
        // 调用userMapper的updateInfoByUid(User user)方法执行修改,并获取返回值
        Integer rows = userMapper.updateInfoByUid(user);
        if (rows != 1) {
            throw new UpdateException("更新数据时产生未知的异常");
        }
    }

    @Override
    public void changeAvatar(Integer uid, String avatar, String username) {
        //查询当前用户数据是否存在
        User result = userMapper.findByUid(uid);
        if (result == null || result.getIsDelete().equals(1)) {
            throw new UserNotFoundException("用户数据不存在");
        }
        Integer rows = userMapper.updateAvatarByUid(uid, avatar, username, new Date());
        if (rows != 1) {
            throw new UpdateException("更新用户头像产生未知的异常");
        }
    }

    
    private String getMD5Password(String password, String salt) {
        for (int i = 0; i < 3; i++) {
            //md5加密算法的调用(进行三次加密)
            password = DigestUtils.md5DigestAsHex((salt + password + salt).getBytes()).toUpperCase();
        }
        //返回加密后的密码
        return password;
    }
}

AddressServiceImpl.java
package com.lll.store.service.impl;

import com.lll.store.entity.Address;
import com.lll.store.mapper.AddressMapper;
import com.lll.store.service.IAddressService;
import com.lll.store.service.IDistrictService;
import com.lll.store.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
public class AddressServiceImpl implements IAddressService {
    @Autowired
    private AddressMapper addressMapper;
    // 在添加用户的收货地址的业务层依赖于IDistrictService的业务层接口
    @Autowired
    private IDistrictService districtService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${user.address.max-count}")
    private int maxCount;

    @Override
    
    public void addNewAddress(Integer uid, String username, Address address) {
        // 根据参数uid调用addressMapper的countByUid(Integer uid)方法,统计当前用户的收货地址数据的数量
        Integer count = addressMapper.countByUid(uid);
        // 判断数量是否达到上限值
        if (count > maxCount) {
            // 是:抛出AddressCountLimitException
            throw new AddressCountLimitException("收货地址数量已经达到上限(" + maxCount + ")!");
        }

        // 补全数据:省、市、区的名称
        String provinceName = districtService.getNameByCode(address.getProvinceCode());
        String cityName = districtService.getNameByCode(address.getCityCode());
        String areaName = districtService.getNameByCode(address.getAreaCode());
        address.setProvinceName(provinceName);
        address.setCityName(cityName);
        address.setAreaName(areaName);

        // 补全数据:将参数uid封装到参数address中
        address.setUid(uid);
        // 补全数据:根据以上统计的数量,得到正确的isDefault值(是否默认:0-不默认,1-默认),并封装
        Integer isDefault = count == 0 ? 1 : 0;
        address.setIsDefault(isDefault);
        // 补全数据:4项日志
        Date now = new Date();
        address.setCreatedUser(username);
        address.setCreatedTime(now);
        address.setModifiedUser(username);
        address.setModifiedTime(now);

        // 调用addressMapper的insert(Address address)方法插入收货地址数据,并获取返回的受影响行数
        Integer rows = addressMapper.insert(address);
        // Redis存入缓存
        redisTemplate.opsForValue().set("address_" + address.getAid(), address);
        // 判断受影响行数是否不为1
        if (rows != 1) {
            // 是:抛出InsertException
            throw new InsertException("插入收货地址数据时出现未知错误,请联系系统管理员!");
        }
    }

    @Override
    public List
getByUid(Integer uid) { List
list = addressMapper.findByUid(uid); // for (Address address : list) { // address.setAid(null); // address.setUid(null); // address.setProvinceCode(null); // address.setCityCode(null); // address.setAreaCode(null); // address.setCreatedUser(null); // address.setCreatedTime(null); // address.setModifiedUser(null); // address.setModifiedTime(null); // } return list; } @Override public void setDefault(Integer aid, Integer uid, String username) { // 根据参数aid,调用addressMapper中的findByAid()查询收货地址数据 Address result = addressMapper.findByAid(aid); // 判断查询结果是否为null if (result == null) { // 是:抛出AddressNotFoundException throw new AddressNotFoundException("尝试访问的收货地址数据不存在"); } // 判断查询结果中的uid与参数uid是否不一致(使用equals()判断) if (!result.getUid().equals(uid)) { // 是:抛出AccessDeniedException throw new AccessDeniedException("非法访问的异常"); } // 调用addressMapper的updateNonDefaultByUid()将该用户的所有收货地址全部设置为非默认,并获取返回受影响的行数 Integer rows = addressMapper.updateNonDefaultByUid(uid); // 判断受影响的行数是否小于1(不大于0) if (rows < 1) { // 是:抛出UpdateException throw new UpdateException("设置默认收货地址时出现未知错误[1]"); } // 调用addressMapper的updateDefaultByAid()将指定aid的收货地址设置为默认,并获取返回的受影响的行数 rows = addressMapper.updateDefaultByAid(aid, username, new Date()); // 判断受影响的行数是否不为1 if (rows != 1) { // 是:抛出UpdateException throw new UpdateException("设置默认收货地址时出现未知错误[2]"); } } @Override public void delete(Integer aid, Integer uid, String username) { // 根据参数aid,调用findByAid()查询收货地址数据 Address result = addressMapper.findByAid(aid); // 判断查询结果是否为null if (result == null) { // 是:抛出AddressNotFoundException throw new AddressNotFoundException("尝试访问的收货地址数据不存在"); } // 判断查询结果中的uid与参数uid是否不一致(使用equals()判断) if (!result.getUid().equals(uid)) { // 是:抛出AccessDeniedException:非法访问 throw new AccessDeniedException("非常访问"); } // 根据参数aid,调用deleteByAid()执行删除 Integer rows1 = addressMapper.deleteByAid(aid); if (rows1 != 1) { throw new DeleteException("删除收货地址数据时出现未知错误,请联系系统管理员"); } // 判断查询结果中的isDefault是否为0 if (result.getIsDefault() == 0) { return; } // 调用持久层的countByUid()统计目前还有多少收货地址 Integer count = addressMapper.countByUid(uid); // 判断目前的收货地址的数量是否为0 if (count == 0) { return; } // 调用findLastModified()找出用户最近修改的收货地址数据 Address lastModified = addressMapper.findLastModified(uid); // 从以上查询结果中找出aid属性值 Integer lastModifiedAid = lastModified.getAid(); // 调用持久层的updateDefaultByAid()方法执行设置默认收货地址,并获取返回的受影响的行数 Integer rows2 = addressMapper.updateDefaultByAid(lastModifiedAid, username, new Date()); // 判断受影响的行数是否不为1 if (rows2 != 1) { // 是:抛出UpdateException throw new UpdateException("更新收货地址数据时出现未知错误,请联系系统管理员"); } } //提交订单获取地址 @Override public Address getByAid(Integer aid, Integer uid) { // 根据收货地址数据id,查询收货地址详情 Address address = addressMapper.findByAid(aid); if (address == null) { throw new AddressNotFoundException("尝试访问的收货地址数据不存在"); } if (!address.getUid().equals(uid)) { throw new AccessDeniedException("非法访问"); } address.setProvinceCode(null); address.setCityCode(null); address.setAreaCode(null); address.setCreatedUser(null); address.setCreatedTime(null); address.setModifiedUser(null); address.setModifiedTime(null); return address; } }
DistrictServiceImpl.java
package com.lll.store.service.impl;

import com.lll.store.entity.District;
import com.lll.store.mapper.DistrictMapper;
import com.lll.store.service.IDistrictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class DistrictServiceImpl implements IDistrictService {
    @Autowired
    private DistrictMapper districtMapper;

    @Override
    public List getByParent(String parent) {
        List list = districtMapper.findByParent(parent);
        for (District district : list) {
            district.setId(null);
            district.setParent(null);
        }
        return list;
    }

    @Override
    public String getNameByCode(String code) {
        return districtMapper.findNameByCode(code);
    }
}

ProductServiceImpl.java
package com.lll.store.service.impl;

import com.lll.store.entity.Product;
import com.lll.store.mapper.ProductMapper;
import com.lll.store.service.IProductService;
import com.lll.store.service.ex.ProductNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class ProductServiceImpl implements IProductService {
    @Autowired
    private ProductMapper productMapper;

    @Override
    public List findHotList() {
        List list = productMapper.findHotList();
        for (Product product : list) {
            product.setPriority(null);
            product.setCreatedUser(null);
            product.setCreatedTime(null);
            product.setModifiedUser(null);
            product.setModifiedTime(null);
        }
        return list;
    }

    @Override
    public Product findById(Integer id) {
        // 根据参数id调用私有方法执行查询,获取商品数据
        Product product = productMapper.findById(id);
        // 判断查询结果是否为null
        if (product == null) {
            // 是:抛出ProductNotFoundException
            throw new ProductNotFoundException("尝试访问的商品数据不存在");
        }
        // 将查询结果中的部分属性设置为null
        product.setPriority(null);
        product.setCreatedUser(null);
        product.setCreatedTime(null);
        product.setModifiedUser(null);
        product.setModifiedTime(null);
        // 返回查询结果
        return product;
    }
}

CartServiceImpl.java
package com.lll.store.service.impl;

import com.lll.store.entity.Cart;
import com.lll.store.entity.Product;
import com.lll.store.mapper.CartMapper;
import com.lll.store.mapper.ProductMapper;
import com.lll.store.service.ICartService;
import com.lll.store.service.IProductService;
import com.lll.store.service.ex.AccessDeniedException;
import com.lll.store.service.ex.CartNotFoundException;
import com.lll.store.service.ex.InsertException;
import com.lll.store.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Iterator;
import java.util.List;


@Service
public class CartServiceImpl implements ICartService {
    // 购物车的业务层依赖于购物车的持久层以及商品的持久层
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public void addToCart(Integer uid, Integer pid, Integer amount, String username) {
        // 根据参数pid和uid查询购物车中的数据
        Cart result = cartMapper.findByUidAndPid(uid, pid);
        Date now = new Date();
        // 判断查询结果是否为null
        if (result == null) {
            // 是:表示该用户并未将该商品添加到购物车
            // 创建Cart对象
            Cart cart = new Cart();
            // 封装数据:uid,pid,amount
            cart.setUid(uid);
            cart.setPid(pid);
            cart.setNum(amount);
            // 调用productService.findById(pid)查询商品数据,得到商品价格,来自于商品中的数据
            Product product = productMapper.findById(pid);
            // 封装数据:price
            cart.setPrice(product.getPrice());
            // 封装数据:4个日志
            cart.setCreatedUser(username);
            cart.setCreatedTime(now);
            cart.setModifiedUser(username);
            cart.setModifiedTime(now);
            // 调用insert(cart)执行将数据插入到数据表中
            Integer rows = cartMapper.insert(cart);
            if (rows != 1) {
                throw new InsertException("插入商品数据时出现未知错误,请联系系统管理员");
            }
        } else {
            // 否:表示该用户的购物车中已有该商品
            // 从查询结果中获取购物车数据的id
            Integer cid = result.getCid();
            // 从查询结果中取出原数量,与参数amount相加,得到新的数量
            Integer num = result.getNum() + amount;
            // 执行更新数量
            Integer rows = cartMapper.updateNumByCid(cid, num, username, now);
            if (rows != 1) {
                throw new InsertException("修改商品数量时出现未知错误,请联系系统管理员");
            }
        }
    }

    @Override
    public List getVOByUid(Integer uid) {
        return cartMapper.findVOByUid(uid);
    }

    @Override
    public Integer addNum(Integer cid, Integer uid, String username) {
        // 调用findByCid(cid)根据参数cid查询购物车数据
        Cart result = cartMapper.findByCid(cid);
        // 判断查询结果是否为null
        if (result == null) {
            // 是:抛出CartNotFoundException
            throw new CartNotFoundException("尝试访问的购物车数据不存在");
        }

        // 判断查询结果中的uid与参数uid是否不一致
        if (!result.getUid().equals(uid)) {
            // 是:抛出AccessDeniedException
            throw new AccessDeniedException("非法访问");
        }

        // 可选:检查商品的数量是否大于多少(适用于增加数量)或小于多少(适用于减少数量)
        // 根据查询结果中的原数量增加1得到新的数量num
        Integer num = result.getNum() + 1;

        // 创建当前时间对象,作为modifiedTime
        Date now = new Date();
        // 调用updateNumByCid(cid, num, modifiedUser, modifiedTime)执行修改数量
        Integer rows = cartMapper.updateNumByCid(cid, num, username, now);
        if (rows != 1) {
            throw new InsertException("修改商品数量时出现未知错误,请联系系统管理员");
        }

        // 返回新的数量
        return num;
    }

    @Override
    public List getVOByCids(Integer uid, Integer[] cids) {
        List list = cartMapper.findVOByCids(cids);
		
        Iterator it = list.iterator();
        while (it.hasNext()) {
            CartVO cart = it.next();
            if (!cart.getUid().equals(uid)) {// 表示当前数据不属于当前用户
                // 从集合中一处这个元素
                it.remove();
            }
        }
        return list;
    }
}

OrderServiceImpl.java
package com.lll.store.service.impl;

import com.lll.store.entity.Address;
import com.lll.store.entity.Order;
import com.lll.store.entity.OrderItem;
import com.lll.store.mapper.OrderMapper;
import com.lll.store.service.IAddressService;
import com.lll.store.service.ICartService;
import com.lll.store.service.IOrderService;
import com.lll.store.service.ex.InsertException;
import com.lll.store.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private ICartService cartService;

    @Transactional
    @Override
    public Order create(Integer aid, Integer[] cids, Integer uid, String username) {
        // 创建当前时间对象
        Date now = new Date();

        // 根据cids查询所勾选的购物车列表中的数据
        List carts = cartService.getVOByCids(uid, cids);

        // 计算这些商品的总价
        long totalPrice = 0;
        for (CartVO cart : carts) {
            totalPrice += cart.getRealPrice() * cart.getNum();
        }

        // 创建订单数据对象
        Order order = new Order();
        // 补全数据:uid
        order.setUid(uid);
        // 查询收货地址数据
        Address address = addressService.getByAid(aid, uid);
        // 补全数据:收货地址相关的6项
        order.setRecvName(address.getName());
        order.setRecvPhone(address.getPhone());
        order.setRecvProvince(address.getProvinceName());
        order.setRecvCity(address.getCityName());
        order.setRecvArea(address.getAreaName());
        order.setRecvAddress(address.getAddress());
        // 补全数据:totalPrice
        order.setTotalPrice(totalPrice);
        // 补全数据:status
        order.setStatus(0);
        // 补全数据:下单时间
        order.setOrderTime(now);
        // 补全数据:日志
        order.setCreatedUser(username);
        order.setCreatedTime(now);
        order.setModifiedUser(username);
        order.setModifiedTime(now);
        // 插入订单数据
        Integer rows1 = orderMapper.insertOrder(order);
        if (rows1 != 1) {
            throw new InsertException("插入订单数据时出现未知错误,请联系系统管理员");
        }

        // 遍历carts,循环插入订单商品数据
        for (CartVO cart : carts) {
            // 创建订单商品数据
            OrderItem item = new OrderItem();
            // 补全数据:setOid(order.getOid())
            item.setOid(order.getOid());
            // 补全数据:pid, title, image, price, num
            item.setPid(cart.getPid());
            item.setTitle(cart.getTitle());
            item.setImage(cart.getImage());
            item.setPrice(cart.getRealPrice());
            item.setNum(cart.getNum());
            // 补全数据:4项日志
            item.setCreatedUser(username);
            item.setCreatedTime(now);
            item.setModifiedUser(username);
            item.setModifiedTime(now);
            // 插入订单商品数据
            Integer rows2 = orderMapper.insertOrderItem(item);
            if (rows2 != 1) {
                throw new InsertException("插入订单商品数据时出现未知错误,请联系系统管理员");
            }
        }

        // 返回
        return order;
    }
}

八、controller ex FileEmptyException.java
package com.lll.store.controller.ex;


public class FileEmptyException extends FileUploadException {
    public FileEmptyException() {
        super();
    }

    public FileEmptyException(String message) {
        super(message);
    }

    public FileEmptyException(String message, Throwable cause) {
        super(message, cause);
    }

    public FileEmptyException(Throwable cause) {
        super(cause);
    }

    protected FileEmptyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

FileSizeException.java
package com.lll.store.controller.ex;


public class FileSizeException extends FileUploadException {
    public FileSizeException() {
        super();
    }

    public FileSizeException(String message) {
        super(message);
    }

    public FileSizeException(String message, Throwable cause) {
        super(message, cause);
    }

    public FileSizeException(Throwable cause) {
        super(cause);
    }

    protected FileSizeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

FileStateException.java
package com.lll.store.controller.ex;


public class FileStateException extends FileUploadException {
    public FileStateException() {
        super();
    }

    public FileStateException(String message) {
        super(message);
    }

    public FileStateException(String message, Throwable cause) {
        super(message, cause);
    }

    public FileStateException(Throwable cause) {
        super(cause);
    }

    protected FileStateException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

FileTypeException.java
package com.lll.store.controller.ex;


public class FileTypeException extends FileUploadException {
    public FileTypeException() {
        super();
    }

    public FileTypeException(String message) {
        super(message);
    }

    public FileTypeException(String message, Throwable cause) {
        super(message, cause);
    }

    public FileTypeException(Throwable cause) {
        super(cause);
    }

    protected FileTypeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

FileUploadException.java
package com.lll.store.controller.ex;


public class FileUploadException extends RuntimeException {
    public FileUploadException() {
        super();
    }

    public FileUploadException(String message) {
        super(message);
    }

    public FileUploadException(String message, Throwable cause) {
        super(message, cause);
    }

    public FileUploadException(Throwable cause) {
        super(cause);
    }

    protected FileUploadException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

FileUploadIOException.java
package com.lll.store.controller.ex;


public class FileUploadIOException extends FileUploadException {
    public FileUploadIOException() {
        super();
    }

    public FileUploadIOException(String message) {
        super(message);
    }

    public FileUploadIOException(String message, Throwable cause) {
        super(message, cause);
    }

    public FileUploadIOException(Throwable cause) {
        super(cause);
    }

    protected FileUploadIOException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

控制器 UserController.java
package com.lll.store.controller;

import com.lll.store.controller.ex.*;
import com.lll.store.entity.User;
import com.lll.store.service.IUserService;
import com.lll.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("users")
public class UserController extends BaseController {
    @Autowired
    private IUserService userService;

    
    @PostMapping("reg")
    public JsonResult reg(User user) {
        userService.reg(user);
        return new JsonResult(OK);
    }

    

    
    @RequestMapping("login")
    public JsonResult login(String username, String password, HttpSession session) {
        User data = userService.login(username, password);
        //向session对象中完成数据的绑定(session全局的)
        session.setAttribute("uid", data.getUid());
        session.setAttribute("username", data.getUsername());

        //获取session中绑定的数据
//        System.out.println(getuidFromSession(session));
//        System.out.println(getUsernameFromSession(session));
        return new JsonResult(OK, data);
    }

    @RequestMapping("change_password")
    public JsonResult changePassword(String oldPassword, String newPassword, HttpSession session) {
//        System.out.println("lllllll");
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
//        System.out.println(uid);
        userService.changePassword(uid, username, oldPassword, newPassword);
        return new JsonResult(OK);
    }

    @RequestMapping("get_by_uid")
    public JsonResult getByUid(HttpSession session) {
        User data = userService.getByUid(getUidFromSession(session));
        return new JsonResult<>(OK, data);
    }

    @RequestMapping("change_info")
    public JsonResult changeInfo(User user, HttpSession session) {
        // user对象有四部分的数据:username、phone、Email、gender、
        // uid数据需要再次封装到user对象中
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.changeInfo(uid, username, user);
        return new JsonResult<>(OK);
    }

    
    public static final int AVATAR_MAX_SIZE = 10 * 1024 * 1024;

    
    public static final List AVATAR_TYPE = new ArrayList<>();

    static {
        AVATAR_TYPE.add("images/jpeg");
        AVATAR_TYPE.add("images/png");
        AVATAR_TYPE.add("images/bmp");
        AVATAR_TYPE.add("images/gif");
    }

    
    @RequestMapping("change_avatar")
    public JsonResult changeAvatar(HttpSession session, @RequestParam("file") MultipartFile file) {
        // 判断文件是否为null
        if (file.isEmpty()) {
            throw new FileEmptyException("文件为空");
        }
        if (file.getSize() > AVATAR_MAX_SIZE) {
            throw new FileSizeException("文件超出限制");
        }
        // 判断文件的类型是否包含我们规定的后缀类型
        String contentType = file.getContentType();
        // 如果集合包含某个元素则返回值true
        if (AVATAR_TYPE.contains(contentType)) {
            throw new FileTypeException("文件类型不支持");
        }
        // 上传的文件.../upload/文件.png
        String parent = session.getServletContext().getRealPath("upload");
        // File对象指向这个路径,File是否存在
        File dir = new File(parent);
        if (!dir.exists()) {// 检测目录是否存在
            dir.mkdirs();//创建当前的目录
        }
        // 获取到这个文件名称,UUID工具来将生成一个新的字符串作为文件名
        // 例如:avatar01.png
        String originalFilename = file.getOriginalFilename();
        System.out.println("originalFilename=" + originalFilename);
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);

        String filename = UUID.randomUUID().toString().toUpperCase() + suffix;
        File dest = new File(dir, filename);// 是一个空文件
        // 参数file中数据写入到这个空文件中
        try {
            file.transferTo(dest);// 将file文件中的数据写入到dest文件
        } catch (FileStateException e) {
            throw new FileStateException("文件状态异常");
        } catch (IOException e) {
            throw new FileUploadIOException("文件读写异常");
        }

        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        // 返回头像的路径/upload/test.png
        String avatar = "/upload/" + filename;
        userService.changeAvatar(uid, avatar, username);
        // 返回用户头像的路径给前端页面,将来用于头像展示使用
        return new JsonResult<>(OK,avatar);
    }
}

BaseController.java
package com.lll.store.controller;

import com.lll.store.controller.ex.*;
import com.lll.store.entity.User;
import com.lll.store.service.ex.*;
import com.lll.store.util.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;


public class BaseController {
    //操作成功的状态码
    public static final int OK = 200;

    //请求处理方法,这个方法的返回值就是需要传递给前端的数据
    //自动将异常对象传递给此方法的参数列表上
    //当前项目中产生了异常,被统一拦截到此方法中,这个方法此时就充当的是请求处理方法,方法的返回值会直接给到前端
    @ExceptionHandler({ServiceException.class, FileUploadException.class})//用于统一处理抛出的异常
    public JsonResult handleException(Throwable e) {
        JsonResult result = new JsonResult<>(e);
        if (e instanceof UsernameDuplicatedException) {
            result.setState(4000);
            result.setMessage("用户名已经被占用");
        } else if (e instanceof UserNotFoundException) {
            result.setState(5001);
            result.setMessage("用户数据不存在的异常");
        } else if (e instanceof PasswordNotMatchException) {
            result.setState(5002);
            result.setMessage("用户名的密码错误的异常");
        } else if (e instanceof AddressCountLimitException) {
            result.setState(4003);
            result.setMessage("用户的收货地址超出上限异常");
        } else if (e instanceof AddressNotFoundException) {
            result.setState(4004);
            result.setMessage("用户的收货地址数据不存在的异常");
        } else if (e instanceof AccessDeniedException) {
            result.setState(4005);
            result.setMessage("收货地址数据非法访问的异常");
        } else if (e instanceof ProductNotFoundException) {
            result.setState(4006);
            result.setMessage("商品不存在的异常");
        } else if (e instanceof InsertException) {
            result.setState(5000);
            result.setMessage("注册时产生未知的异常");
        } else if (e instanceof InsertException) {
            result.setState(5001);
            result.setMessage("更新数据时产生未知的异常");
        } else if (e instanceof DeleteException) {
            result.setState(5002);
            result.setMessage("删除数据时产生未知的异常");
        } else if (e instanceof FileEmptyException) {
            result.setState(6000);
        } else if (e instanceof FileSizeException) {
            result.setState(6001);
        } else if (e instanceof FileTypeException) {
            result.setState(6002);
        } else if (e instanceof FileStateException) {
            result.setState(6003);
        } else if (e instanceof FileUploadIOException) {
            result.setState(6004);
        }
        return result;
    }

    
    protected final Integer getUidFromSession(HttpSession session) {
        return Integer.valueOf(session.getAttribute("uid").toString());
    }

    
    protected final String getUsernameFromSession(HttpSession session) {
        return session.getAttribute("username").toString();
    }
}

AddressController.java
package com.lll.store.controller;

import com.lll.store.entity.Address;
import com.lll.store.service.IAddressService;
import com.lll.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@RequestMapping("addresses")
@RestController
public class AddressController extends BaseController {
    @Autowired
    private IAddressService addressService;

    @RequestMapping("add_new_address")
    public JsonResult addNewAddress(Address address, HttpSession session) {
        // 从Session中获取uid和username
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);

        // 调用业务对象的方法执行业务
        addressService.addNewAddress(uid, username, address);
        // 响应成功
        return new JsonResult(OK);
    }

    //    @RequestMapping({"", "/"}) 字符串和斜杠都可以
    @RequestMapping({"", "/"})
    public JsonResult> getByUid(HttpSession session) {
        Integer uid = getUidFromSession(session);
        List
data = addressService.getByUid(uid); return new JsonResult>(OK, data); } @RequestMapping("{aid}/set_default") public JsonResult setDefault(@PathVariable("aid") Integer aid, HttpSession session) { Integer uid = getUidFromSession(session); String username = getUsernameFromSession(session); addressService.setDefault(aid, uid, username); return new JsonResult(OK); } @RequestMapping("{aid}/delete") public JsonResult delete(@PathVariable("aid") Integer aid, HttpSession session) { Integer uid = getUidFromSession(session); String username = getUsernameFromSession(session); addressService.delete(aid, uid, username); return new JsonResult(OK); } }
DistrictController.java
package com.lll.store.controller;

import com.lll.store.entity.District;
import com.lll.store.service.IDistrictService;
import com.lll.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("districts")
public class DistrictController extends BaseController {
    @Autowired
    private IDistrictService districtService;

    //districts开头的请求都被拦截到getByParent方法
    @RequestMapping({"/", ""})
    //@RequestMapping(method={RequestMethod.GET})
    public JsonResult> getByParent(String parent) {
        List data = districtService.getByParent(parent);
        return new JsonResult<>(OK, data);
    }
}

ProductController.java
package com.lll.store.controller;

import com.lll.store.entity.Product;
import com.lll.store.service.IProductService;
import com.lll.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("products")
public class ProductController extends BaseController {
    @Autowired
    private IProductService productService;

    @RequestMapping("hot_list")
    public JsonResult> getHotList() {
        List data = productService.findHotList();
        return new JsonResult>(OK, data);
    }

    @GetMapping("{id}/details")
    public JsonResult getById(@PathVariable("id") Integer id) {
        // 调用业务对象执行获取数据
        Product data = productService.findById(id);
        // 返回成功和数据
        return new JsonResult(OK, data);
    }
}

CartController.java
package com.lll.store.controller;

import com.lll.store.service.ICartService;
import com.lll.store.util.JsonResult;
import com.lll.store.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("carts")
public class CartController extends BaseController {
    @Autowired
    private ICartService cartService;

    @RequestMapping("add_to_cart")
    public JsonResult addToCart(Integer pid, Integer amount, HttpSession session) {
//        System.out.println("pid=" + pid);
//        System.out.println("amount=" + amount);
        // 从Session中获取uid和username
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        // 调用业务对象执行添加到购物车
        cartService.addToCart(uid, pid, amount, username);
        // 返回成功
        return new JsonResult(OK);
    }

    @GetMapping({"", "/"})
    public JsonResult> getVOByUid(HttpSession session) {
        // 从Session中获取uid
        Integer uid = getUidFromSession(session);
        // 调用业务对象执行查询数据
        List data = cartService.getVOByUid(uid);
        // 返回成功与数据
        return new JsonResult>(OK, data);
    }

    @RequestMapping("{cid}/num/add")
    public JsonResult addNum(@PathVariable("cid") Integer cid, HttpSession session) {
        // 从Session中获取uid和username
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        // 调用业务对象执行增加数量
        Integer data = cartService.addNum(cid, uid, username);
        // 返回成功
        return new JsonResult(OK, data);
    }

    @GetMapping("list")
    public JsonResult> getVOByCids(Integer[] cids, HttpSession session) {
        // 从Session中获取uid
        Integer uid = getUidFromSession(session);
        // 调用业务对象执行查询数据
        List data = cartService.getVOByCids(uid, cids);
        // 返回成功与数据
        return new JsonResult<>(OK, data);
    }
}

OrderController.java
package com.lll.store.controller;

import com.lll.store.entity.Order;
import com.lll.store.service.IOrderService;
import com.lll.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("orders")
public class OrderController extends BaseController {
    @Autowired
    private IOrderService orderService;

    @RequestMapping("create")
    public JsonResult create(Integer aid, Integer[] cids, HttpSession session) {
        // 从Session中取出uid和username
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        // 调用业务对象执行业务
        Order data = orderService.create(aid, cids, uid, username);
        // 返回成功与数据
        return new JsonResult(OK, data);
    }
}


总结

数据库文件和前端页面我都放gitee了
gieee地址

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/847131.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号