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.mzph.cn/news/820218.shtml

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

相关文章

【canvas】canvas基础使用(九):文本绘制

简言 canvas除了能够绘制图形外&#xff0c;也可以绘制文本。 绘制文本 fillText() 填充文本 CanvasRenderingContext2D 对象的方法 fillText() 是 Canvas 2D API 的一部分&#xff0c;它在指定的坐标上绘制文本字符串&#xff0c;并使用当前的 fillStyle 对其进行填充。存…

论文解读:FREE LUNCH FOR FEW-SHOT LEARNING: DISTRIBUTION CALIBRATION

文章汇总 问题 学习到的模型很容易因为只有少数训练样本形成的有偏分布而变得过拟合。 动机 我们假设特征表示中的每个维度都遵循高斯分布&#xff0c;因此分布的均值和方差可以借鉴类似类的均值和方差&#xff0c;这些类的统计量可以通过足够数量的样本得到更好的估计。 …

11.盛最多水的容器(Java,双指针)

目录 题目描述&#xff1a;输入&#xff1a;输出&#xff1a;代码实现&#xff1a; 题目描述&#xff1a; 给定一个长度为 n 的整数数组 height 。有 n 条垂线&#xff0c;第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。 找出其中的两条线&#xff0c;使得它们与 x 轴共同…

Vue - 5( 16000 字 Vue2 入门级教程)

一&#xff1a;Vue 初阶 1.1 组件自定义事件 在 Vue 中&#xff0c;组件间通过自定义事件进行通信是一种常见的模式。自定义事件允许子组件向父组件发送消息&#xff0c;也可以在组件内部进行事件的绑定、触发和解绑。让我们详细讲解这些知识点。 1.1.1 组件自定义事件 在 …

季节更迭 关爱不变 | 鲁南制药四季守护您的健康生活

春天&#xff0c;万物复苏的季节&#xff0c;一切都充满了生机和活力。在春日的阳光下&#xff0c;鲜花盛开&#xff0c;绿叶茂盛&#xff0c;鸟儿欢歌&#xff0c;蝴蝶翩翩起舞。我们的身体也需要特别的关爱和养护&#xff0c;保持健康和活力&#xff0c;更好地迎接每一次季节…

知识跟踪模型GraphKT

1 知识跟踪Knowledge Tracing的概念 知识跟踪可以用来解决自适应学习问题。如何通过与教学材料的在线互动来有效地跟踪学生的学习进展&#xff1f;知识跟踪可用于量化学生的知识状态&#xff0c;即对教材所涉及的技能掌握水平。用于评估和模拟学生随着时间推移对技能的认知掌握…

前端CSS讲义1

什么是 CSS? CSS 指层叠样式表 样式定义如何显示 HTML 元素 样式通常存储在样式表中 把样式添加到 HTML 4.0 中&#xff0c;是为了解决内容与表现分离的问题 外部样式表可以极大提高工作效率 外部样式表通常存储在 CSS 文件中 多个样式定义可层叠为一 样式对网页中元素…

AI数字人对话之RealChar框架源码解读

零.功能介绍 与虚拟角色(非形象)进行文本或语音会话 体验地址:RealChar. 代码库:GitHub - Shaunwei/RealChar: 🎙️🤖Create, Customize and Talk to your AI Character/Companion in Realtime (All in One Codebase!). Have a natural seamless conversation with AI…

姿态估计-人脸识别mesh-3d手势识别-3d目标检测-背景分割-人脸关键点

往期热门博客项目回顾&#xff1a;点击前往 计算机视觉项目大集合 改进的yolo目标检测-测距测速 路径规划算法 图像去雨去雾目标检测测距项目 交通标志识别项目 yolo系列-重磅yolov9界面-最新的yolo 姿态识别-3d姿态识别 深度学习小白学习路线 AI健身教练-引体向上…

字节8年经验之谈 —— 聊一聊自动化测试为什么很难落地!

聊一聊自动化测试为什么很难落地 在软件开发和质量保障的领域&#xff0c;测试是确保软件质量的关键环节。自动化测试是一种利用脚本和工具自动执行测试用例的方法&#xff0c;可以提高测试效率、减少人工错误&#xff0c;并支持持续集成和交付。自动化测试作为提高测试效率和…

企业图纸管理软件,企业图纸管理软件有哪些推荐?

企业图纸管理软件是一种专门用于组织、存储、管理和共享企业图纸及相关文档的工具。这类软件可以帮助企业实现图纸的集中化、规范化管理&#xff0c;提高工作效率&#xff0c;降低管理成本。 企业图纸管理软件的核心功能通常包括以下几个方面&#xff1a; 集中化管理&#xff1…

bestvike --bvframe学习

ref title fetch后台api 分页属性&#xff0c;pagination 要差几条&#xff1f;pagelimit 在api中写一个饭方法&#xff0c;vue中用用他 vue.cinfig.js中配置别名 nacos微服务 实体类要继承basedata&#xff08;封装了公共数据&#xff09; 控制器autowired&#xff0c;getm…

lua 环境安装

下载地址&#xff1a; https://luabinaries.sourceforge.net/download.html 安装环境变量 检查一下是否安装成功&#xff0c;有版本号&#xff0c;打印一句话&#xff0c;如下表示成功 idea 安装插件&#xff0c;方便编写lua脚本 配置一下idea 运行测试 local function m…

Linux的重要命令(二)+了解Linux目录结构

目录 一.Linux的目录结构 二.查看文件内容命令 1.cat 命令 2.more 命令 3.less 命令 4.head 命令 5.tail 命令 6.拓展 head 和 tail 的其他用法 ​编辑 三.统计文件内容的命令-wc ​编辑 四.检索和过滤文件内容的命令-grep ​编辑 ​编辑 五.压缩命令 gzip 和 bz…

【SpringBoot】返回参数

返回参数 返回页面返回数据返回 html 代码返回 json 数据两数相加用户登录 返回页面 首先在 static 文件夹中创建 index.html 文件&#xff1a; 代码&#xff1a; <html> <body><h1>hello word!!!</h1><p>this is a html page</p> <…

JS-29-Promise对象

一、JavaScript的异步操作 在JavaScript的世界中&#xff0c;所有代码都是单线程执行的。 由于这个“缺陷”&#xff0c;导致JavaScript的所有网络操作&#xff0c;浏览器事件&#xff0c;都必须是异步执行。异步执行可以用回调函数实现&#xff1a; function callback() {c…

temux安装debian自用记录

http://ip:9001/ user/123 http://ip:5705/index admin/drpy 一、安装Ubuntu1804 1&#xff0e;首先安装termux.app 2&#xff0e;启动该app&#xff0c;输入命令 curl -Lo l l.tmoe.me; sh l 3&#xff0e;运行过程中连续选“Y”&…

ip数据报

IP数据报格式详解 在 TCP/IP 协议中&#xff0c;使用 IP 协议传输数据的包被称为 IP 数据包&#xff0c;每个数据包都包含 IP 协议规定的内容。IP 协议规定的这些内容被称为 IP 数据报文&#xff08;IP Datagram&#xff09;或者 IP 数据报。 IP 数据报文由首部&#xff08;称…

Linux学习-数据库

数据库软件: 关系型数据库: Mysql Oracle SqlServer Sqlite 非关系型数据库&#xff1a; Redis NoSQL 1.数组、链表、文件、数据库 数组、链表: 内存存放数据的方式(代码运行结束、关机数据丢失) 文件、…

GitHub repository - Branch - SSH clone URL - Clone in Desktop - Download ZIP

GitHub repository - Branch - SSH clone URL - Clone in Desktop - Download ZIP 1. Branch2. SSH clone URL3. Clone in Desktop4. Download ZIPReferences 1. Branch 显示当前分支的名称。从这里可以切换仓库内分支&#xff0c;查看其他分支的文件。 2. SSH clone U…