007 springboot整合mybatis-plus 增删改查 ModelAndView jsp 分页

文章目录

    • MybatisplusConfig.java
    • ReceiveAddressController.java
    • ReceiveAddress.java
    • ReceiveAddressMapper.java
    • ReceiveAddressServiceImpl.java
    • IReceiveAddressService.java
    • ServerResult.java
    • ServletInitializer.java
    • SpringbootDemoApplication.java
    • receive_address.sql
    • ReceiveAddressMapper.xml
    • application.yaml
    • detail.jsp
    • list.jsp(忽略)
    • listPage.jsp
    • save.jsp
    • update.jsp
    • web.xml
    • index.jsp
    • pom.xml
    • TestAddressService.java

在这里插入图片描述

MybatisplusConfig.java

package com.example.config;import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration //当前是类配置类 @Component
public class MybatisplusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor(){MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();paginationInnerInterceptor.setDbType(DbType.MYSQL);paginationInnerInterceptor.setOverflow(true);interceptor.addInnerInterceptor(paginationInnerInterceptor);return interceptor;}}

ReceiveAddressController.java

package com.example.controller;import com.example.entity.ReceiveAddress;
import com.example.service.IReceiveAddressService;
import com.example.util.ServerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;import java.time.LocalDateTime;
import java.util.List;/*** <p>*  前端控制器* </p>** @author dd* @since 2024-04-10*/@Controller
@RequestMapping("/receiveAddress")
public class ReceiveAddressController {@Autowiredprivate IReceiveAddressService addressService;/*** 根据主键查询* @param arrId* @return*/@GetMapping("{addrId}") //URL:http://localhost:8080/app/receiveAddress/1public ModelAndView getById(@PathVariable("addrId") Integer arrId){//URL :  http://localhost:8080/app/receiveAddress/1//System.out.println("addrId:" +arrId);//1.调用serviceServerResult result = addressService.getById(arrId);//System.out.println("result:" + result);ModelAndView modelAndView = new ModelAndView();//2数据绑定modelAndView.addObject("result" ,result);//数据//3.页面跳转 receiveAddress/detail.jspmodelAndView.setViewName("receiveAddress/detail");return modelAndView;}/*** 查询所有     //URL :  http://localhost:8080/app/receiveAddress/* @return*/@GetMapping("")public ModelAndView getAll(){int custId = 1;// 模拟的登录用户id//ServerResult result = addressService.getAll(custId);ServerResult result = addressService.getByPage(1,1);ModelAndView mav = new ModelAndView();//2数据绑定mav.addObject("result",result);//3页面跳转 receiveAddress/list.jspmav.setViewName("receiveAddress/listPage");return mav;}/*** 新增收件地址* @param receiveAddress* @return*/@PostMappingpublic ModelAndView save(ReceiveAddress receiveAddress){int customerId = 1;  //用户idreceiveAddress.setCustId(customerId);//receiveAddress.setStatus(1);//receiveAddress.setVersion(1);//receiveAddress.setCreateTime(LocalDateTime.now());ServerResult result = addressService.save(receiveAddress);ModelAndView mav = new ModelAndView();//1.添加成功,查询所有if(result.getCode() == 200){mav.setViewName("redirect:/receiveAddress");// controller}else {mav.addObject("result",result);mav.setViewName("/receiveAddress/save");// .jsp}return mav;}/*** 删除(修改status=0)* @param addressId 根据主键删除(根据主键修改)* @return*/@DeleteMapping("/{addrId}")public ModelAndView remove(@PathVariable("addrId") Integer addressId){System.out.println("删除id="+addressId +"的地址");ServerResult result = addressService.removeById(addressId);ModelAndView mav = new ModelAndView();if(result.getCode() == 200){System.out.println("删除成功");mav.setViewName("redirect:/receiveAddress");}else {mav.setViewName("receiveAddress/listPage");mav.addObject("deleteMsg","删除失败");}return mav;}@GetMapping("update/{addrId}") //URL:http://localhost:8080/app/receiveAddress/1public ModelAndView getByIdForUpdate(@PathVariable("addrId") Integer arrId){//URL :  http://localhost:8080/app/receiveAddress/1//System.out.println("addrId:" +arrId);//1.调用serviceServerResult result = addressService.getById(arrId);//System.out.println("result:" + result);ModelAndView modelAndView = new ModelAndView();//2数据绑定modelAndView.addObject("result" ,result);//数据//3.页面跳转 receiveAddress/updatemodelAndView.setViewName("receiveAddress/update");return modelAndView;}/*** 修改某一个收件地址信息* @param address 页面中接受到的最新的收件地址信息* @return*/@PutMappingpublic  ModelAndView update(ReceiveAddress address){   //put :   http://localhost:8080/app/coupon/address.setUpdateTime(LocalDateTime.now());ServerResult result =   addressService.updateById(address);ModelAndView modelAndView =   new ModelAndView();if(result.getCode() == 200){//修改成功//跳转到地址详情页面(根据主键查询)modelAndView.setViewName("redirect:/receiveAddress/"+address.getAddrId());}else{//修改失败//跳转到update.jsp 提示修改失败modelAndView.addObject("updateMsg","修改失败");modelAndView.setViewName("update");}return modelAndView;}@GetMapping("page/{pageNum}")public ModelAndView getByPage(@PathVariable("pageNum") Integer pageNum){ServerResult result = addressService.getByPage(pageNum,1);ModelAndView mav = new ModelAndView();mav.addObject("result",result);mav.setViewName("receiveAddress/listPage");return mav;}}

ReceiveAddress.java

package com.example.entity;import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.time.LocalDateTime;/*** <p>* * </p>** @author dd* @since 2024-04-10*/
@TableName("receive_address")
public class ReceiveAddress implements Serializable {private static final long serialVersionUID = 1L;@TableId(value = "addr_id", type = IdType.AUTO)private Integer addrId;private Long receiveUserTelno;private String receiveUsername;private Integer custId;/*** 地址的省份*/private String addrProvince;/*** 地址的城市*/private String addrCity;/*** 地址的区域*/private String addrArea;/*** 地址的街道*/private String addrStreet;/*** 详细地址*/private String addrDetail;/*** 状态*/private Integer status;/*** 版本号,用于做乐观锁*/private Integer version;/*** 数据添加的时间*/private LocalDateTime createTime;/*** 数据修改时间*/private LocalDateTime updateTime;public Integer getAddrId() {return addrId;}public void setAddrId(Integer addrId) {this.addrId = addrId;}public Long getReceiveUserTelno() {return receiveUserTelno;}public void setReceiveUserTelno(Long receiveUserTelno) {this.receiveUserTelno = receiveUserTelno;}public String getReceiveUsername() {return receiveUsername;}public void setReceiveUsername(String receiveUsername) {this.receiveUsername = receiveUsername;}public Integer getCustId() {return custId;}public void setCustId(Integer custId) {this.custId = custId;}public String getAddrProvince() {return addrProvince;}public void setAddrProvince(String addrProvince) {this.addrProvince = addrProvince;}public String getAddrCity() {return addrCity;}public void setAddrCity(String addrCity) {this.addrCity = addrCity;}public String getAddrArea() {return addrArea;}public void setAddrArea(String addrArea) {this.addrArea = addrArea;}public String getAddrStreet() {return addrStreet;}public void setAddrStreet(String addrStreet) {this.addrStreet = addrStreet;}public String getAddrDetail() {return addrDetail;}public void setAddrDetail(String addrDetail) {this.addrDetail = addrDetail;}public Integer getStatus() {return status;}public void setStatus(Integer status) {this.status = status;}public Integer getVersion() {return version;}public void setVersion(Integer version) {this.version = version;}public LocalDateTime getCreateTime() {return createTime;}public void setCreateTime(LocalDateTime createTime) {this.createTime = createTime;}public LocalDateTime getUpdateTime() {return updateTime;}public void setUpdateTime(LocalDateTime updateTime) {this.updateTime = updateTime;}@Overridepublic String toString() {return "ReceiveAddress{" +"addrId=" + addrId +", receiveUserTelno=" + receiveUserTelno +", receiveUsername=" + receiveUsername +", custId=" + custId +", addrProvince=" + addrProvince +", addrCity=" + addrCity +", addrArea=" + addrArea +", addrStreet=" + addrStreet +", addrDetail=" + addrDetail +", status=" + status +", version=" + version +", createTime=" + createTime +", updateTime=" + updateTime +"}";}
}

ReceiveAddressMapper.java

package com.example.mapper;import com.example.entity.ReceiveAddress;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;/*** <p>*  Mapper 接口* </p>** @author dd* @since 2024-04-10*/
public interface ReceiveAddressMapper extends BaseMapper<ReceiveAddress> {}

ReceiveAddressServiceImpl.java

package com.example.service.impl;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.ReceiveAddress;
import com.example.mapper.ReceiveAddressMapper;
import com.example.service.IReceiveAddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.util.ServerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.time.LocalDateTime;
import java.util.List;/*** <p>*  服务实现类* </p>** @author dd* @since 2024-04-10*/
@Service
public class ReceiveAddressServiceImpl  implements IReceiveAddressService {@Autowiredprivate  ReceiveAddressMapper addressMapper;@Overridepublic ServerResult getById(Integer addressId) {ReceiveAddress address = addressMapper.selectById(addressId);if(address != null){return ServerResult.getSuccess(address);}return ServerResult.getFail(null);}//当前登录用户的有效地址@Overridepublic ServerResult getAll(Integer customerId){//select * fromQueryWrapper<ReceiveAddress> wrapper = new QueryWrapper<>();wrapper.eq("cust_id",customerId).eq("status",1);List<ReceiveAddress> addressList = addressMapper.selectList(wrapper);//select * from table_name where cust_id= andif(addressList == null || addressList.size()==0)return ServerResult.getFail("暂无收件地址");return ServerResult.getSuccess(addressList);}//添加public ServerResult save(ReceiveAddress receiveAddress){//receiveAddress: 没有addr_idreceiveAddress.setStatus(1);receiveAddress.setVersion(1);receiveAddress.setCreateTime(LocalDateTime.now());System.out.println("尚未添加,从页面拿到的收件地址是:" + receiveAddress);int rows = addressMapper.insert(receiveAddress);if(rows > 0){System.out.println("添加成功后:" + receiveAddress);return ServerResult.updateSuccess(receiveAddress);//若添加成功,会把数据库中自增的主键addr_id赋值到对象上}return ServerResult.updateFail(receiveAddress);}//删除收件地址(实际修改status为0)@Overridepublic ServerResult removeById(Integer addressId) {ReceiveAddress address = addressMapper.selectById(addressId);address.setStatus(0);address.setVersion(address.getVersion() + 1);int rows = addressMapper.updateById(address);//删除成功row =1,删除失败row=0if(rows > 0)return ServerResult.updateSuccess(address);return ServerResult.updateFail(address);}@Overridepublic ServerResult updateById(ReceiveAddress address) {int oldVersion = addressMapper.selectById(address.getAddrId()).getVersion();//旧的version值来自dbaddress.setUpdateTime(LocalDateTime.now());address.setVersion(oldVersion+1);int rows = addressMapper.updateById(address);if(rows > 0){return ServerResult.updateSuccess(address);}return ServerResult.updateFail(address);}@Overridepublic ServerResult getByPage(Integer pageNum,Integer customerId) {//select * from address where cust_id = 1 and status = 1 limit 0,3//select * from address where cust_id = 1 and status = 1 limit 3,3//select * from address where cust_id = 1 and status = 1 limit 6,3QueryWrapper<ReceiveAddress> wrapper = new QueryWrapper<>();wrapper.eq("cust_id",customerId).eq("status",1);//page:只有页面的信息(当前页码、每页显示记录数)Page<ReceiveAddress> page = new Page<>(pageNum,3);//page:页码的信息+数据page = addressMapper.selectPage(page,wrapper);if (page.getRecords().size() > 0){return ServerResult.getSuccess(page);}return ServerResult.getFail(page);}}

IReceiveAddressService.java


package com.example.service;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.ReceiveAddress;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.util.ServerResult;import java.util.List;/*** <p>*  服务类* </p>** @author dd* @since 2024-04-10*/
public interface IReceiveAddressService  {public ServerResult getById(Integer addressId);//查询所有的收件地址(当前用户有效的地址数据)public ServerResult getAll(Integer customerId);public ServerResult save(ReceiveAddress receiveAddress);public ServerResult removeById(Integer addressId);public ServerResult updateById(ReceiveAddress address);//分页查询public ServerResult getByPage(Integer pageNum,Integer customerId);}

ServerResult.java


package com.example.util;public class ServerResult {private int code;private String msg;private Object data;public static ServerResult getSuccess(Object data){return new ServerResult(200,"查询成功",data);}public static ServerResult getFail(Object data){return new ServerResult(201,"查询失败",data);}/*** 添加、删除、修改的成功* @param data* @return*/public static ServerResult updateSuccess(Object data){return new ServerResult(200,"处理成功",data);}/*** 添加、删除、修改的失败* @param data* @return*/public static ServerResult updateFail(Object data){return new ServerResult(201,"处理失败",data);}public static ServerResult loginSuccess(Object data){return new ServerResult(200,"登录成功",data);}public static ServerResult loginFail(Object data){return new ServerResult(201,"登失败",data);}public ServerResult() {}public ServerResult(int code, String msg, Object data) {this.code = code;this.msg = msg;this.data = data;}public int getCode() {return code;}public void setCode(int code) {this.code = code;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public Object getData() {return data;}public void setData(Object data) {this.data = data;}@Overridepublic String toString() {return "ServerResult{" +"code=" + code +", msg='" + msg + '\'' +", data=" + data +'}';}
}

ServletInitializer.java


package com.example;import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;public class ServletInitializer extends SpringBootServletInitializer {@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder application) {return application.sources(SpringbootDemoApplication.class);}}

SpringbootDemoApplication.java


package com.example;import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
@MapperScan("com.example.mapper")
public class SpringbootDemoApplication {public static void main(String[] args) {SpringApplication.run(SpringbootDemoApplication.class, args);}}

receive_address.sql

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for receive_address
-- ----------------------------
DROP TABLE IF EXISTS `receive_address`;
CREATE TABLE `receive_address`  (`addr_id` int(0) NOT NULL AUTO_INCREMENT,`receive_user_telno` bigint(0) NULL DEFAULT NULL,`receive_username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,`cust_id` int(0) NULL DEFAULT NULL,`addr_province` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '地址的省份',`addr_city` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '地址的城市',`addr_area` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '地址的区域',`addr_street` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '地址的街道',`addr_detail` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '详细地址',`status` int(0) NULL DEFAULT NULL COMMENT '状态',`version` int(0) NULL DEFAULT NULL COMMENT '版本号,用于做乐观锁',`create_time` datetime(0) NULL DEFAULT NULL COMMENT '数据添加的时间',`update_time` datetime(0) NULL DEFAULT NULL COMMENT '数据修改时间',PRIMARY KEY (`addr_id`) USING BTREE,INDEX `fk_address_customer`(`cust_id`) USING BTREE,CONSTRAINT `fk_address_customer` FOREIGN KEY (`cust_id`) REFERENCES `customer` (`cust_id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;-- ----------------------------
-- Records of receive_address
-- ----------------------------
INSERT INTO `receive_address` VALUES (1, NULL, NULL, 1, '江苏省', '苏州市', '园区', '若水路', '若水路', 1, 1, '2023-08-11 13:47:02', NULL);
INSERT INTO `receive_address` VALUES (2, NULL, NULL, 1, '黑龙江', '大庆市', '市区', '育才路', '育才路', 1, 1, '2023-07-31 13:47:52', NULL);SET FOREIGN_KEY_CHECKS = 1;

ReceiveAddressMapper.xml

<?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.example.mapper.ReceiveAddressMapper"></mapper>

application.yaml


server:servlet:context-path: /appport: 8080spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/dicts?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghaiusername: rootpassword: 123456mvc:view:prefix: / #前缀suffix: .jsp #后缀hiddenmethod:filter:enabled: true # 支持表单 method 转换

detail.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>收件地址详情</title>
</head>
<body>
收件人姓名:${result.data.receiveUsername} <br>
手机号:${result.data.receiveUserTelno}<br>
收件地址:${result.data.addrProvince}${result.data.addrCity}${result.data.addrArea}${result.data.addrStreet}${result.data.addrDetail}</body>
</html>

list.jsp(忽略)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head><title>收件地址列表</title><script src="${pageContext.request.contextPath}/js/jquery-3.7.0.min.js"></script><style>body {font-family: Arial, sans-serif;background-color: #f4f4f4;margin: 0;padding: 0;}.container {max-width: 600px;margin: 20px auto;padding: 20px;background-color: #fff;border-radius: 8px;box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);}h2 {margin-top: 0;}.address-list {list-style-type: none;padding: 0;}.address-list li {background-color: #f9f9f9;padding: 20px;margin-bottom: 20px;border-radius: 8px;box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);position: relative;}.address-list li h3 {margin-top: 0;margin-bottom: 10px;}.address-list li p {margin: 0;margin-bottom: 5px;}.address-list li .btn-container {position: absolute;top: 20px;right: 20px;}.deleteForm{width: 45px;height: 30px;display: block;float: left;}.address-list li .delete-btn, .address-list li .update-btn {background-color: #007bff;color: #fff;border: none;border-radius: 4px;padding: 8px 12px;cursor: pointer;text-decoration: none;font-size: 10px;display:block;float: left;margin-right: 10px;}.address-list li .delete-btn:hover,.address-list li .update-btn:hover {background-color: #0056b3;}.pagination {margin-top: 20px;text-align: center;}.pagination button {background-color: #007bff;color: #fff;border: none;border-radius: 4px;padding: 8px 16px;cursor: pointer;margin: 0 5px;}.pagination button:hover {background-color: #0056b3;}</style>
</head>
<body>${deleteMsg}<c:if test="${result.code !=200}">暂无数据
</c:if>
<c:if test="${result.code ==200}"><div class="container"><h2>我的收件地址列表</h2><ul class="address-list" id="addressList"><c:forEach var="address" items="${result.data}"><li><div class="btn-container"><%-- 修改: 根据主键查询 到修改页面  --%><a href="${pageContext.request.contextPath}/receiveAddress/update/${address.addrId}" class="update-btn">修改</a><%-- 通过表单的隐藏域,将post请求 转换成 delete 请求    --%><form class="deleteForm" method="post" action="${pageContext.request.contextPath}/receiveAddress/${address.addrId}"><input type="hidden" name="_method" value="DELETE"><input type="button" value="删除" class="delete-btn"></form></div><h3>${address.receiveUsername}</h3><p>手机号: ${address.receiveUserTelno}</p><p>收件地址: ${address.addrProvince}${address.addrCity}${address.addrArea}${address.addrStreet}${address.addrDetail}</p></li></c:forEach></ul></div>
</c:if><script>// 事件冒泡document.querySelector(".address-list").onclick = function(event){var ele =  event.target; // 目标元素if(ele.nodeName =='INPUT' && ele.className =='delete-btn'){console.log(ele);if(window.confirm("您要删除这条记录么?")){ele.parentElement.submit();}}}</script>
</body>
</html>

listPage.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head><title>收件地址列表</title><script src="${pageContext.request.contextPath}/js/jquery-3.7.0.min.js"></script><style>body {font-family: Arial, sans-serif;background-color: #f4f4f4;margin: 0;padding: 0;}.container {max-width: 600px;margin: 20px auto;padding: 20px;background-color: #fff;border-radius: 8px;box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);}h2 {margin-top: 0;}.address-list {list-style-type: none;padding: 0;}.address-list li {background-color: #f9f9f9;padding: 20px;margin-bottom: 20px;border-radius: 8px;box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);position: relative;}.address-list li h3 {margin-top: 0;margin-bottom: 10px;}.address-list li p {margin: 0;margin-bottom: 5px;}.address-list li .btn-container {position: absolute;top: 20px;right: 20px;}.deleteForm{width: 45px;height: 30px;display: block;float: left;}.address-list li .delete-btn, .address-list li .update-btn {background-color: #007bff;color: #fff;border: none;border-radius: 4px;padding: 8px 12px;cursor: pointer;text-decoration: none;font-size: 10px;display:block;float: left;margin-right: 10px;}.address-list li .delete-btn:hover,.address-list li .update-btn:hover {background-color: #0056b3;}.pagination {margin-top: 20px;text-align: center;}.pagination button {background-color: #007bff;color: #fff;border: none;border-radius: 4px;padding: 8px 16px;cursor: pointer;margin: 0 5px;}.pagination button:hover {background-color: #0056b3;}</style>
</head>
<body>${result}<c:if test="${result.code !=200}">暂无数据
</c:if>
<c:if test="${result.code ==200}"><div class="container"><h2>我的收件地址列表</h2><ul class="address-list" id="addressList"><c:forEach var="address" items="${result.data.records}"><li><div class="btn-container"><%-- 修改: 根据主键查询 到修改页面  --%><a href="${pageContext.request.contextPath}/receiveAddress/update/${address.addrId}" class="update-btn">修改</a><%-- 通过表单的隐藏域,将post请求 转换成 delete 请求    --%><form class="deleteForm" method="post" action="${pageContext.request.contextPath}/receiveAddress/${address.addrId}"><input type="hidden" name="_method" value="DELETE"><input type="button" value="删除" class="delete-btn"></form></div><h3>${address.receiveUsername}</h3><p>手机号: ${address.receiveUserTelno}</p><p>收件地址: ${address.addrProvince}${address.addrCity}${address.addrArea}${address.addrStreet}${address.addrDetail}</p></li></c:forEach></ul><div><c:if test="${result.data.current !=1}"><a href="${pageContext.request.contextPath}/receiveAddress/page/${result.data.current-1}">上一页</a></c:if>当前是${result.data.current} 页,共有${result.data.total}  条记录,共有${result.data.pages}页<c:if test="${result.data.current !=result.data.pages}"><a href="${pageContext.request.contextPath}/receiveAddress/page/${result.data.current+1}">下一页</a></c:if></div></div>
</c:if><script>// 事件冒泡document.querySelector(".address-list").onclick = function(event){var ele =  event.target; // 目标元素if(ele.nodeName =='INPUT' && ele.className =='delete-btn'){console.log(ele);if(window.confirm("您要删除这条记录么?")){ele.parentElement.submit();}}}</script>
</body>
</html>

save.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>添加收件地址</title><style>body {font-family: Arial, sans-serif;background-color: #f4f4f4;margin: 0;padding: 0;}.container {max-width: 600px;margin: 20px auto;padding: 20px;background-color: #fff;border-radius: 8px;box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);}h2 {margin-top: 0;}input[type="text"],input[type="tel"],select {width: 100%;padding: 10px;margin-top: 8px;margin-bottom: 20px;border: 1px solid #ccc;border-radius: 4px;box-sizing: border-box;}button {background-color: #007bff;color: #fff;border: none;border-radius: 4px;padding: 12px 20px;cursor: pointer;}button:hover {background-color: #0056b3;}</style>
</head>
<body>
<div class="container"><h2>添加收件地址</h2><%--    ${pageContext.request.contextPath} ===>  http://localhost:8080/app   --%><form id="addressForm" method="post" action="${pageContext.request.contextPath}/receiveAddress"><label for="recipientName">收件人姓名:</label><input type="text" id="recipientName" name="receiveUsername" required><label for="phoneNumber">收件人手机号:</label><input type="tel" id="phoneNumber" name="receiveUserTelno"  required><label for="province">省份:</label><select id="province" name="addrProvince" required><option value="">请选择省份</option><option value="北京">北京</option><option value="上海">上海</option><option value="天津">天津</option><option value="重庆">重庆</option><option value="河北">河北</option><option value="河南">河南</option><option value="湖南">湖南</option><option value="湖北">湖北</option><option value="四川">四川</option><option value="广东">广东</option></select><label for="city">城市:</label><select id="city" name="addrCity" required><option value="">请选择城市</option></select><label for="district">区域:</label><input type="text" id="district" name="addrArea" required><label for="street">街道:</label><input type="text" id="street" name="addrStreet" required><label for="address">详细地址:</label><input type="text" id="address" name="addrDetail" required><input type="submit" value="添加 " /></form>
</div><script>// Cities data for each provincevar citiesData = {"北京": ["北京"],"上海": ["上海"],"天津": ["天津"],"重庆": ["重庆"],"河北": ["石家庄", "唐山", "保定"],"河南": ["郑州", "洛阳", "开封"],"湖南": ["长沙", "株洲", "湘潭"],"湖北": ["武汉", "黄石", "十堰"],"四川": ["成都", "绵阳", "乐山"],"广东": ["广州", "深圳", "东莞"]};// Function to populate cities based on selected provincefunction populateCities() {var provinceSelect = document.getElementById("province");var citySelect = document.getElementById("city");var selectedProvince = provinceSelect.value;// Clear existing city optionscitySelect.innerHTML = "<option value=''>Select City</option>";// Populate city options based on selected provinceif (selectedProvince in citiesData) {citiesData[selectedProvince].forEach(function(city) {var option = document.createElement("option");option.value = city;option.text = city;citySelect.appendChild(option);});}}// Event listener for province select changedocument.getElementById("province").addEventListener("change", populateCities);</script>
</body>
</html>

update.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>修改收件地址</title><style>body {font-family: Arial, sans-serif;background-color: #f4f4f4;margin: 0;padding: 0;}.container {max-width: 600px;margin: 20px auto;padding: 20px;background-color: #fff;border-radius: 8px;box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);}h2 {margin-top: 0;}input[type="text"],input[type="tel"],select {width: 100%;padding: 10px;margin-top: 8px;margin-bottom: 20px;border: 1px solid #ccc;border-radius: 4px;box-sizing: border-box;}button {background-color: #007bff;color: #fff;border: none;border-radius: 4px;padding: 12px 20px;cursor: pointer;}button:hover {background-color: #0056b3;}</style>
</head>
<body>
<div class="container">${updateMsg}<h2>修改收件地址</h2><%--1. post -- put2. 底层根据什么修改地址的???SQL???update address set 列1=值,列2=值2....  where addr_id = 101--%><form id="addressForm" method="post" action="${pageContext.request.contextPath}/receiveAddress"><%--1. post -- put  --%><input type="hidden" name="_method" value="PUT"><%--2.底层根据id修改地址的,通过隐藏域传给服务器      --%><input type="hidden" name="addrId" value="${result.data.addrId}"><label for="recipientName">收件人姓名:</label><input type="text" id="recipientName" name="receiveUsername"  value="${result.data.receiveUsername}" required><label for="phoneNumber">收件人手机号:</label><input type="tel" id="phoneNumber" name="receiveUserTelno" value="${result.data.receiveUserTelno}"   required><label for="province">省份:</label><select id="province" name="addrProvince" required><option value="${result.data.addrProvince}">${result.data.addrProvince}</option><option value="北京">北京</option><option value="上海">上海</option><option value="天津">天津</option><option value="重庆">重庆</option><option value="河北">河北</option><option value="河南">河南</option><option value="湖南">湖南</option><option value="湖北">湖北</option><option value="四川">四川</option><option value="广东">广东</option></select><label for="city">城市:</label><select id="city" name="addrCity" required><option value="${result.data.addrCity}">${result.data.addrCity}</option></select><label for="district">区域:</label><input type="text" id="district" name="addrArea" value="${result.data.addrArea}" required><label for="street">街道:</label><input type="text" id="street" name="addrStreet" value="${result.data.addrStreet}" required><label for="address">详细地址:</label><input type="text" id="address" name="addrDetail" value="${result.data.addrDetail}" required><input type="submit" value="修改 " /></form>
</div><script>// Cities data for each provincevar citiesData = {"北京": ["北京"],"上海": ["上海"],"天津": ["天津"],"重庆": ["重庆"],"河北": ["石家庄", "唐山", "保定"],"河南": ["郑州", "洛阳", "开封"],"湖南": ["长沙", "株洲", "湘潭"],"湖北": ["武汉", "黄石", "十堰"],"四川": ["成都", "绵阳", "乐山"],"广东": ["广州", "深圳", "东莞"]};// Function to populate cities based on selected provincefunction populateCities() {var provinceSelect = document.getElementById("province");var citySelect = document.getElementById("city");var selectedProvince = provinceSelect.value;// Clear existing city optionscitySelect.innerHTML = "<option value=''>Select City</option>";// Populate city options based on selected provinceif (selectedProvince in citiesData) {citiesData[selectedProvince].forEach(function(city) {var option = document.createElement("option");option.value = city;option.text = city;citySelect.appendChild(option);});}}// Event listener for province select changedocument.getElementById("province").addEventListener("change", populateCities);</script>
</body>
</html>

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"version="4.0">
</web-app>

index.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>
<a href="receiveAddress/1" >根据主键查询收件地址</a> <br><a href="receiveAddress" >查询我的所有收件地址(分页)</a><a href="receiveAddress/save.jsp" >添加新收件地址</a><a href="${pageContext.request.contextPath}/receiveAddress/page/1">查询所有收件地址(分页)</a></body>
</html>

pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.6</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>springboot_demo</artifactId><version>0.0.1-SNAPSHOT</version><packaging>war</packaging><name>springboot_demo</name><description>springboot_demo</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><dependency><groupId>taglibs</groupId><artifactId>standard</artifactId><version>1.1.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-tomcat</artifactId><scope>provided</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.28</version></dependency><!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.2</version></dependency><!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-generate --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.5.1</version></dependency><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.31</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

TestAddressService.java


package com.example;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.ReceiveAddress;
import com.example.service.IReceiveAddressService;
import com.example.util.ServerResult;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
public class TestAddressService {@Autowiredprivate IReceiveAddressService service;@Testpublic void getByPage(){ServerResult result = service.getByPage(2,1);Page<ReceiveAddress> page =  (   Page<ReceiveAddress>) result.getData();System.out.println("当前页码:"+page.getCurrent());System.out.println("总记录数:"+page.getTotal());System.out.println("总页数:"+page.getPages());System.out.println("地址数据");page.getRecords().forEach(System.out::println);}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/623446.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

python接口自动化测试 —— unittest框架suite、runner详细使用

test suite 测试套件&#xff0c;理解成测试用例集一系列的测试用例&#xff0c;或测试套件&#xff0c;理解成测试用例的集合和测试套件的集合当运行测试套件时&#xff0c;则运行里面添加的所有测试用例 test runner 测试运行器用于执行和输出结果的组件 test suite、tes…

DBUtils工具类的使用

1、DBUtils是什么 为了更加简单地使用JDBC&#xff0c;Apache组织提供了一个DBUtils工具&#xff0c;它是操作数据库的一个组件&#xff0c;实现了对JDBC的简单封装&#xff0c;可以在不影响数据库访问性能的情况下简化JDBC的编码工作量。DBUtils工具要有2个作用。 写数据&am…

Upload-labs(Pass-14 - Pass-16)

Pass-14 &#xff08;图片马&#xff0c;判断文件类型&#xff09; 图片的格式在防护中通常是不会使用后缀进行判断的依据&#xff0c;文件头是文件开头的一段二进制码&#xff0c;不同类型的图片也就会有不同的二进制头。   JPEG (jpg)&#xff0c;文件头&#xff1a;FF D…

C++从入门到精通——类的6个默认成员函数之赋值运算符重载

赋值运算符重载 前言一、运算符重载定义实例注意要点 二、赋值运算符重载赋值运算符重载格式赋值运算符重载要点重载要点传值返回和传址返回要点 三、前置和后置重载 前言 类的6个默认成员函数&#xff1a;如果一个类中什么成员都没有&#xff0c;简称为空类。 空类中真的什么…

ESP32S3在wsl环境的JTAG、openocd仿真调试

文章目录 一、准备工作二、添加 ESP-IDF 环境变量三、添加 udev 规则文件四、vscode 配置 一、准备工作 安装配置好 WSL、ubuntu, 参考连接&#xff1a; WSL2安装Ubuntu迁移到其他盘或者其他电脑_wsl ubuntu迁移-CSDN博客 WSL2 设置桥接模式_wsl2 桥接-CSDN博客 下载好 WSL-US…

Python 物联网入门指南(八)

原文&#xff1a;zh.annas-archive.org/md5/4fe4273add75ed738e70f3d05e428b06 译者&#xff1a;飞龙 协议&#xff1a;CC BY-NC-SA 4.0 第三十章&#xff1a;制作机械臂 最后&#xff0c;我们终于到达了大多数人自本书开始以来就想要到达的地方。制作一个机械臂&#xff01;在…

游戏生成式 AI:编织梦想,避开阴影

想象一下&#xff0c;一个沉浸式的游戏世界中玩家遇到的每个 NPC 都由 AI 驱动&#xff0c;他们能与玩家进行互动&#xff0c;从改变游戏体验。据 Inword 一项研究显示&#xff0c;绝大多数游戏玩家渴望这种互动&#xff0c;愿意投入更多的时间和金钱来玩这种由 AI 驱动的游戏。…

Linux_iptables防火墙学习笔记

文章目录 iptables 概述四表五链iptables 安装启动iptables 配置详解iptables配置文件iptables配置语法iptables常用实例查看规则修改默认规则保存和备份规则恢复备份的规则清空规则放行SSH服务在ubuntu14.04中iptables规则持久化 iptables 概述 主机型 对主机进行保护 网络型…

020——SPI模块驱动开发(基于DAC芯片和I.MX6uLL)

目录 一、 SPI简介 二、 Linux中的SPI 2.1 SPI控制器数据结构 2.2 SPI设备数据结构 2.3 SPI设备驱动 2.4 接口函数 2.4.1 函数原型 2.4.2 函数解析 2.5 SPI驱动框架 2.6 SPI控制器驱动程序 2.7 SPI设备驱动程序 三、 DAC实例 3.1 实验过程 3.2 驱动程序 3.3 应…

Redis--16--Spring Data Redis

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 Spring Data Redishttps://spring.io/projects/spring-data-redis 1.依赖2.RedisTemplate3.案例 序列化1.默认是 JdkSerializationRedisSerializer2.添加Redis配置文…

MySQL基础-----约束详解

目录 一. 概述: 二.约束演示&#xff1a; 三.外键约束&#xff1a; 3.1介绍&#xff1a; 3.2外键约束语法&#xff1a; 3.3删除&#xff0c;更新行为&#xff1a; 一. 概述: &#x1f9d0;&#x1f9d0;概念&#xff1a;约束是作用于表中字段上的规则&#xff0c;用于限制…

抖店创业日记:24年的抖音电商市场,“慢”比“快”更重要~

我是王路飞。 今天是2024年4月16日。 距离我坚持做抖店10年的目标&#xff0c;还有6年2个月的时间。 做抖店之前&#xff0c;我做过天猫、京东、快手等平台&#xff0c;随着时间的推移&#xff0c;愈加感觉到一个真理&#xff1a;只要不下牌桌&#xff0c;就永远不会失去机会…