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

本文主要是介绍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

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>

这篇关于007 springboot整合mybatis-plus 增删改查 ModelAndView jsp 分页的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/898692

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

mybatis的整体架构

mybatis的整体架构分为三层: 1.基础支持层 该层包括:数据源模块、事务管理模块、缓存模块、Binding模块、反射模块、类型转换模块、日志模块、资源加载模块、解析器模块 2.核心处理层 该层包括:配置解析、参数映射、SQL解析、SQL执行、结果集映射、插件 3.接口层 该层包括:SqlSession 基础支持层 该层保护mybatis的基础模块,它们为核心处理层提供了良好的支撑。

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory

【C++ Primer Plus习题】13.4

大家好,这里是国中之林! ❥前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看← 问题: 解答: main.cpp #include <iostream>#include "port.h"int main() {Port p1;Port p2("Abc", "Bcc", 30);std::cout <<