🍁
博客主页:
👉@不会压弯的小飞侠
✨欢迎关注:
👉点赞
👍收藏
⭐留言
✒
✨系列专栏:
👉SpringBoot电商项目实战
✨学习社区:
👉不会压弯的小飞侠
✨知足上进,不负野心。
🔥欢迎大佬指正,一起学习!一起加油!
🍁创建数据表
- 在store数据库中创建t_address用户数据表。
CREATE TABLE t_address (
aid INT AUTO_INCREMENT COMMENT '收货地址id',
uid INT COMMENT '归属的用户id',
name VARCHAR(20) COMMENT '收货人姓名',
province_name VARCHAR(15) COMMENT '省-名称',
province_code CHAR(6) COMMENT '省-行政代号',
city_name VARCHAR(15) COMMENT '市-名称',
city_code CHAR(6) COMMENT '市-行政代号',
area_name VARCHAR(15) COMMENT '区-名称',
area_code CHAR(6) COMMENT '区-行政代号',
zip CHAR(6) COMMENT '邮政编码',
address VARCHAR(50) COMMENT '详细地址',
phone VARCHAR(20) COMMENT '手机',
tel VARCHAR(20) COMMENT '固话',
tag VARCHAR(6) COMMENT '标签',
is_default INT COMMENT '是否默认:0-不默认,1-默认',
created_user VARCHAR(20) COMMENT '创建人',
created_time DATETIME COMMENT '创建时间',
modified_user VARCHAR(20) COMMENT '修改人',
modified_time DATETIME COMMENT '修改时间',
PRIMARY KEY (aid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- 选中store数据库,点击新建查询,然后粘贴代码,点击运行即可。
- t_address表创建成功
🍁创建实体类
- 创建com.jkj.entity.Address新增收获地址的实体类,继承自BaseEntity类,在类中声明与数据表中对应的属性,添加Getters and Setters方法,基于唯一标识aid生成hashCode()和equals()方法。
/** 收货地址数据的实体类 */
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 int hashCode() {
int result = aid != null ? aid.hashCode() : 0;
result = 31 * result + (uid != null ? uid.hashCode() : 0);
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (provinceName != null ? provinceName.hashCode() : 0);
result = 31 * result + (provinceCode != null ? provinceCode.hashCode() : 0);
result = 31 * result + (cityName != null ? cityName.hashCode() : 0);
result = 31 * result + (cityCode != null ? cityCode.hashCode() : 0);
result = 31 * result + (areaName != null ? areaName.hashCode() : 0);
result = 31 * result + (areaCode != null ? areaCode.hashCode() : 0);
result = 31 * result + (zip != null ? zip.hashCode() : 0);
result = 31 * result + (address != null ? address.hashCode() : 0);
result = 31 * result + (phone != null ? phone.hashCode() : 0);
result = 31 * result + (tel != null ? tel.hashCode() : 0);
result = 31 * result + (tag != null ? tag.hashCode() : 0);
result = 31 * result + (isDefault != null ? isDefault.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 +
'}';
}
}
🍁新增收货地址-持久层
- 收货地址数据的管理,涉及的功能有:增加,删除,修改,设为默认,显示列表。这些功能的开发顺序为:增加-显示列表-设为默认-删除-修改。
- 后续在处理业务时,还需要确定“即将增加的收货地址是不是默认收货地址”;可以设定规则“用户的第1条收货地址是默认的,以后添加的每一条都不是默认的”;要应用该规则,就必须知道“即将增加的收货地址是不是第1条”,可以“根据用户id统计收货地址的数量”,如果统计结果为0,则即将增加的就是该用户的第1条收货地址,如果统计结果不是0,则该用户已经有若干条收货地址了,即将增加的就一定不是第1条。
- 每个用户最多只允许创建20个收货地址
🔥 接口与抽象方法
- 创建com.jkj.mapper.AddressMapper接口,并在接口中添加抽象方法。
public interface AddressMapper {
/**
* 插入收货地址数据
* @param address 收货地址数据
* @return 受影响的行数
*/
Integer insert(Address address);
/**
* 统计某用户的收货地址数据的数量
* @param uid 用户的id
* @return 该用户的收货地址数据的数量
*/
Integer countByUid(Integer uid);
}
🔥 配置SQL映射
- 注意:
- 在src/main/resources/mapper文件夹下复制粘贴得到AddressMapper.xml映射文件,修改根节点mapper的namespace属性的值为com.jkj.mapper.AddressMapper,并在根节点中配置pojo类属性与数据库中表的字段映射。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jkj.mapper.AddressMapper">
<resultMap id="AddressEntityMap" type="com.jkj.entity.Address">
<id column="aid" property="aid"/>
<result column="province_code" property="provinceCode"/>
<result column="province_name" property="provinceName"/>
<result column="city_code" property="cityCode"/>
<result column="city_name" property="cityName"/>
<result column="area_code" property="areaCode"/>
<result column="area_name" property="areaName"/>
<result column="is_default" property="isDefault"/>
<result column="created_user" property="createdUser"/>
<result column="created_time" property="createdTime"/>
<result column="modified_user" property="modifiedUser"/>
<result column="modified_time" property="modifiedTime"/>
</resultMap>
<!-- 插入收货地址数据 -->
<insert id="insert">
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}
)
</insert>
<!-- 统计某用户的收货地址数据的数量 -->
<select id="countByUid" resultType="java.lang.Integer">
SELECT COUNT(*) FROM t_address WHERE uid=#{
uid}
</select>
</mapper>
🔥 测试
- 在src/test/java下创建com.jkj.mapper.AddressMapperTests测试类,编写并执行以上两个抽象方法的测试。
// @RunWith(SpringRunner.class)注解是一个测试启动器,可以加载Springboot测试注解
@RunWith(SpringRunner.class)
@SpringBootTest
public class AddressMapperTests {
@Autowired
private AddressMapper addressMapper;
@Test
public void insert(){
Address address = new Address();
address.setUid(8);
address.setName("tom");
address.setPhone("88888888888");
address.setAddress("湖南长沙");
Integer rows = addressMapper.insert(address);
System.out.println("rows=" + rows);
}
@Test
public void countByUid(){
Integer uid = 8;
Integer count = addressMapper.countByUid(uid);
System.out.println("count=" + count);
}
}
- 测试结果
🍁增收货地址-业务层
🔥 异常
- 无论用户将要增加的收货地址是不是默认收货地址,都需正常增加。即通过countByUid()方法统计的结果不管是不是0,都不能代表是错误的操作。
- 在执行插入收货地址数据之前,需判断countByUid()方法返回值是否超出上限值,如果超出上限值则抛AddressCountLimitException异常。
- 在执行插入数据时,还可能抛出InsertException异常,此异常无需再次创建。
- 创建com.jkj.service.exception.AddressCountLimitException类后,需继承自ServiceException类。
/** 收货地址数量达到上限的异常 */
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);
}
}
🔥 接口与抽象方法
- 创建com.jkj.service.IAddressService业务层接口,并添加抽象方法。
public interface IAddressService {
/**
* 创建新的收货地址
* @param uid 当前登录的用户的id
* @param username 当前登录的用户名
* @param address 用户提交的收货地址数据
*/
void addNewAddress(Integer uid, String username, Address address);
}
🔥 实现抽象方法
- 在application.properties文件中添加收货地址数据上限值的配置。
user.address.max-count=20
- 创建com.jkj.service.impl.AddressServiceImpl业务层实现类,在类定义之前添加@Service注解,并实现IAddressService接口,最后在类中添加持久层对象并使用@Autowired注解修饰。
@Service
public class AddressServiceImpl implements IAddressService {
@Autowired
private AddressMapper addressMapper;
@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 + ")!");
}
// 补全数据:将参数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);
// 判断受影响行数是否不为1
if (rows != 1) {
// 是:抛出InsertException
throw new InsertException("插入收货地址数据时出现未知错误,请联系系统管理员!");
}
}
}
🔥 测试
- 在src/test/java下创建com.jkj.service.AddressServiceTests测试类,在测试类中测试以上方法。
@SpringBootTest
class AddressServiceTests {
@Autowired
private IAddressService addressService;
@Test
public void addNewAddress() {
Integer uid = 9;
String username = "xfx";
Address address = new Address();
address.setName("xfx");
address.setPhone("99999999999");
address.setAddress("河南郑州");
addressService.addNewAddress(uid, username, address);
}
}
- 去数据库查看是否插入成功
🍁新增收货地址-控制层
🔥 异常
- 在控制器层新增收货地址时,如果收货地址已经达到上限值,则抛出AddressCountLimitException异常,并在BaseController类中添加处理AddressCountLimitException的异常。
else if (e instanceof AddressCountLimitException) {
result.setState(4003);
}
🔥 用户提交的请求
- 请求路径:/addresses/add_new_address
- 请求参数:Address address, HttpSession session
- 请求类型:POST
- 响应结果:JsonResult
🔥 处理请求
- 创建com.jkj.controller.AddressController控制器类继承自BaseController类,在类的声明添加@RequestMapping(“addresses”)和@RestController注解,在类中声明业务层对象并添加Autowired注解修饰。然后在AddressController类中添加处理请求的addNewAddress(Address address, HttpSession session)方法。
@RestController
@RequestMapping("addresses")
public class AddressController extends BaseController {
@Autowired
private IAddressService addressService;
@RequestMapping("add_new_address")
public JsonResult<Void> addNewAddress(Address address, HttpSession session) {
// 从Session中获取uid和username
Integer uid = getUidFromSession(session);
String username = getUsernameFromSession(session);
// 调用业务对象的方法执行业务
addressService.addNewAddress(uid, username, address);
// 响应成功
return new JsonResult<Void>(OK);
}
}
- 控制层编写完成后,可以启动浏览器进行测试。
- 注意:要先登录
🍁新增收货地址-前端页面
- 在addAddress.html页面中配置新增收货地址表单的属性。给form表单添加id="form-add-new-address"属性、"请输入收货人姓名"添加name="name"属性、"请输入邮政编码"添加name="zip"属性、"输入详细的收货地址,小区名称、门牌号等"添加name="address"属性、"请输入手机号码"添加name="phone"属性、"请输入固定电话号码"添加name="tel"属性、"请输入地址类型,添加name="tag"属性、"保存"按钮添加id="btn-add-new-address"属性。以上属性如果已经添加无需重复添加。
- 在addAddress.html页面中body标签内部的最后,添加script标签用于编写JavaScript程序。
<script type="text/javascript">
$("#btn-add-new-address").click(function() {
$.ajax({
url: "/addresses/add_new_address",
type: "POST",
data: $("#form-add-new-address").serialize(),
dataType: "JSON",
success: function(json) {
if (json.state == 200) {
alert("新增收货地址成功!");
} else {
alert("新增收货地址失败!" + json.message);
}
},
error: function(xhr) {
alert("您的登录信息已经过期,请重新登录!HTTP响应码:" + xhr.status);
location.href = "login.html";
}
});
});
</script>
- 启动项目,打开浏览器先登录,再访问http://localhost:8080/web/login.html页面,先进行登录
- 点击管理,然后点击收货管理,填写信息
- 点击保存后,页面会弹出一个提示框,代表新增地址成功
- 查看t_address表,数据是否插入成功
学习视频:
【SpringBoot项目实战完整版】SpringBoot+MyBatis+MySQL电脑商城项目实战-哔哩哔哩】
https://b23.tv/qGh9x9L
转载:https://blog.csdn.net/qq_43514330/article/details/126509471
查看评论