首页 前端知识 007 springboot整合mybatis-plus 增删改查 ajax(修改部分是) jquery 分页

007 springboot整合mybatis-plus 增删改查 ajax(修改部分是) jquery 分页

2024-04-22 09:04:46 前端知识 前端哥 842 329 我要收藏

文章目录

    • MybatisplusConfig.java
    • ReceiveAddressJsonController.java
    • ReceiveAddress.java
    • ReceiveAddressMapper.java
    • IReceiveAddressService.java
    • ReceiveAddressServiceImpl.java
    • ServerResult.java
    • ServletInitializer.java
    • SpringbootDemoApplication.java
    • receive_address.sql
    • ReceiveAddressMapper.xml
    • application.yaml
    • ajax_demo1.jsp(忽略)
    • ajax_jquery_demo1.jsp
    • pom.xml
    • ajax_demo1.js(忽略)
    • ajax_jquery_demo1.js

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 {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        paginationInnerInterceptor.setDbType(DbType.MYSQL);
        paginationInnerInterceptor.setOverflow(true);

        interceptor.addInnerInterceptor(paginationInnerInterceptor);


        return interceptor;
    }

}



ReceiveAddressJsonController.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 java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dd
 * @since 2024-04-10
 */

@RestController  //@Controller + @ResponseBody 所有方法都返回json数据
@RequestMapping("/receiveAddressJSon")
public class ReceiveAddressJsonController {
    @Autowired
    private IReceiveAddressService addressService;


    /**
     * 根据主键查询
     * @param arrId
     * @return
     */
    @GetMapping("{addrId}") //URL:http://localhost:8080/app/receiveAddress/103
    public ServerResult getById(@PathVariable("addrId") Integer arrId){//URL :  http://localhost:8080/app/receive-address/103

        return addressService.getById(arrId);
    }

    /**
     * 查询所有     //URL :  http://localhost:8080/app/receive-address/
     * @return
     */
    @GetMapping("")
    public ServerResult getAll(){
        int custId = 1;// 模拟的登录用户id
        return addressService.getAll(custId);
    }





    //@GetMapping("page/{pageNum}")
    //public List<ReceiveAddress> getByPage(@PathVariable("pageNum") Integer pageNum){
    //    return null;
    //}


    /**
     * 新增收件地址
     * @param receiveAddress
     * @return
     */
    @PostMapping
    public ServerResult save(ReceiveAddress receiveAddress){
        int customerId = 1;
        receiveAddress.setCustId(customerId);
        receiveAddress.setStatus(1);
        receiveAddress.setVersion(1);
        receiveAddress.setCreateTime(LocalDateTime.now());
        return addressService.save(receiveAddress);

    }


    /**
     * 删除(修改status=0)
     * @param addressId 根据主键删除(根据主键修改)
     * @return
     */
    @DeleteMapping("/{addrId}")
    public ServerResult remove(@PathVariable("addrId") Integer addressId){

        return addressService.removeById(addressId);

    }


    /**
     * 修改我的某一个收件地址信息
     * @param receiveAddress 页面中接受到的最新的收件地址信息
     * @return 返回是否修改成功
     */
    @PutMapping
    public ServerResult update(ReceiveAddress receiveAddress){
        return addressService.updateById(receiveAddress);
    }

    @GetMapping("page/{pageNum}")
    public ServerResult getByPage(@PathVariable("pageNum") Integer pageNum){
        Integer customerId = 1;
        return addressService.getByPage(pageNum,customerId);
    }
}



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;
    }

    @Override
    public 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> {


}




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);






}




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 {



    @Autowired
    private  ReceiveAddressMapper addressMapper;


    @Override
    public ServerResult getById(Integer addressId) {
        ReceiveAddress address = addressMapper.selectById(addressId);
        if(address != null){
            return ServerResult.getSuccess(address);
        }
        return ServerResult.getFail(null);
    }

    //当前登录用户的有效地址
    @Override
    public ServerResult getAll(Integer customerId){
        //select * from
        QueryWrapper<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= and
        if(addressList == null || addressList.size()==0)
            return ServerResult.getFail("暂无收件地址");
        return ServerResult.getSuccess(addressList);



    }



    //添加
    public ServerResult save(ReceiveAddress receiveAddress){//receiveAddress: 没有addr_id

        receiveAddress.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)
    @Override
    public 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=0
        if(rows > 0)
            return ServerResult.updateSuccess(address);
        return ServerResult.updateFail(address);
    }


    @Override
    public ServerResult updateById(ReceiveAddress address) {
        int oldVersion = addressMapper.selectById(address.getAddrId()).getVersion();//旧的version值来自db
        address.setUpdateTime(LocalDateTime.now());
        address.setVersion(oldVersion+1);

        int rows = addressMapper.updateById(address);
        if(rows > 0){
            return ServerResult.updateSuccess(address);
        }
        return ServerResult.updateFail(address);


    }



    @Override
    public 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,3

        QueryWrapper<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);

    }



}




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;
    }


    @Override
    public 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 {

	@Override
	protected 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: /app
  port: 8080

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/dicts?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: 123456
  mvc:
    view:
      prefix: / #前缀
      suffix: .jsp #后缀
    hiddenmethod:
      filter:
        enabled: true # 支持表单 method 转换




ajax_demo1.jsp(忽略)



<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<h1>1.ajax 异步请求:根据主键查询</h1>
<a href="javascript:void(0)" class="getByIdBtn">查询id=1的收件地址</a>

<div class="address_detail">

  收件人姓名:<span class="receive_username"></span><br>
  收件人手机号:<span class="receive_telno"></span><br>
  收件地址:<span class="receive_detail_address"></span><br>


</div>

<div class="address_no_data_info">

  <span></span>
</div>



<%--============================2. ajax 异步请求:添加收件地址=======================================================--%>
<h1>2. ajax 异步请求:添加收件地址</h1>
<form id="addressForm" method="post" action="${pageContext.request.contextPath}/receiveAddress">
  <label for="recipientName">收件人姓名:</label>
  <input type="text" id="recipientName" name="receiveUsername" required> <br>

  <label for="phoneNumber">收件人手机号:</label>
  <input type="tel" id="phoneNumber" name="receiveUserTelno"  required> <br>

  <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>  <br>

  <label for="city">城市:</label>
  <select id="city" name="addrCity" required>
    <option value="">请选择城市</option>
  </select> <br>

  <label for="district">区域:</label>
  <input type="text" id="district" name="addrArea" required> <br>

  <label for="street">街道:</label>
  <input type="text" id="street" name="addrStreet" required> <br>

  <label for="address">详细地址:</label>
  <input type="text" id="address" name="addrDetail" required> <br>

  <input type="button" value="添加 "  class="saveAddressBtn"/>
</form>
<span class="saveMsg"></span>

<script>
  // Cities data for each province
  var citiesData = {
    "北京": ["北京"],
    "上海": ["上海"],
    "天津": ["天津"],
    "重庆": ["重庆"],
    "河北": ["石家庄", "唐山", "保定"],
    "河南": ["郑州", "洛阳", "开封"],
    "湖南": ["长沙", "株洲", "湘潭"],
    "湖北": ["武汉", "黄石", "十堰"],
    "四川": ["成都", "绵阳", "乐山"],
    "广东": ["广州", "深圳", "东莞"]
  };

  // Function to populate cities based on selected province
  function populateCities() {
    var provinceSelect = document.getElementById("province");
    var citySelect = document.getElementById("city");
    var selectedProvince = provinceSelect.value;

    // Clear existing city options
    citySelect.innerHTML = "<option value=''>Select City</option>";

    // Populate city options based on selected province
    if (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 change
  document.getElementById("province").addEventListener("change", populateCities);


</script>
<script src="${pageContext.request.contextPath}/js/ajax_demo1.js"></script>
</body>
</html>



ajax_jquery_demo1.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>ajax-jquery-收件地址</title>
    <script src="${pageContext.request.contextPath}/js/jquery-3.7.0.min.js"></script>
    <script src="${pageContext.request.contextPath}/js/jquery.form.js"></script>

    <style>
        .address_detail{
            display: none;
        }
    </style>
</head>
<body>
<%--============================1. ajax 异步请求:根据主键查询收件地址=======================================================--%>
<h1>1. ajax-jquery 异步请求:根据主键查询收件地址</h1>
<a href="javascript:void(0)" class="getByIdBtn">查询id=1的收件地址</a>

<div class="address_detail">
    收件人姓名:<span class="receive_username"></span> <br>
    收件人手机号:<span class="receive_telno"></span> <br>
    收件地址:<span class="receive_detail_address"></span> <br>
</div>
<div class="address_no_data_info">
    <span ></span>
</div>


<%--============================2. ajax 异步请求:添加收件地址=======================================================--%>
<h1>2. ajax-jquery  异步请求:添加收件地址</h1>
<form id="addressForm" method="post" >
    <label for="recipientName">收件人姓名:</label>
    <input type="text" id="recipientName" name="receiveUsername" required> <br>

    <label for="phoneNumber">收件人手机号:</label>
    <input type="tel" id="phoneNumber" name="receiveUserTelno"  required> <br>

    <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>  <br>

    <label for="city">城市:</label>
    <select id="city" name="addrCity" required>
        <option value="">请选择城市</option>
    </select> <br>

    <label for="district">区域:</label>
    <input type="text" id="district" name="addrArea" required> <br>

    <label for="street">街道:</label>
    <input type="text" id="street" name="addrStreet" required> <br>

    <label for="address">详细地址:</label>
    <input type="text" id="address" name="addrDetail" required> <br>

    <input type="button" value="添加 "  class="saveAddressBtn"/>
</form>
<span class="saveMsg"></span>







<%-- 3.ajax异步请求,查询所有收件地址  --%>
<a href="javascript:void(0)" class="getMyAllAddressBtn">查询所有收件地址(分页)</a>

<%-- 数据信息 --%>
<ul class="address-list" id="addressList">

</ul>

<%-- 页码信息--%>
<div class="page-information">

</div>

<span  class="deleteMsg"></span>















<%--省份城市下拉列表--%>
<script>
    // Cities data for each province
    var citiesData = {
        "北京": ["北京"],
        "上海": ["上海"],
        "天津": ["天津"],
        "重庆": ["重庆"],
        "河北": ["石家庄", "唐山", "保定"],
        "河南": ["郑州", "洛阳", "开封"],
        "湖南": ["长沙", "株洲", "湘潭"],
        "湖北": ["武汉", "黄石", "十堰"],
        "四川": ["成都", "绵阳", "乐山"],
        "广东": ["广州", "深圳", "东莞"]
    };

    // Function to populate cities based on selected province
    function populateCities() {
        var provinceSelect = document.getElementById("province");
        var citySelect = document.getElementById("city");
        var selectedProvince = provinceSelect.value;

        // Clear existing city options
        citySelect.innerHTML = "<option value=''>Select City</option>";

        // Populate city options based on selected province
        if (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 change
    document.getElementById("province").addEventListener("change", populateCities);

</script>

<script src="${pageContext.request.contextPath}/js/ajax_jquery_demo1.js"></script>









</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>




ajax_demo1.js(忽略)


/****1.ajax 异步请求:根据主键查询 ****/

document.querySelector(".getByIdBtn").onclick = function (){

    //1.创建异步请求对象
    var xhr = new XMLHttpRequest();

//2连接服务器
    var url = "http://localhost:80/app/receiveAddressJSon/1"
    xhr.open("GET",url,true);

//3.发送请求
    xhr.send(null);


//4.获得相应数据
    xhr.onreadystatechange = function (){
        if(xhr.readyState == 4 && xhr.status == 200){//http请求响应成功
            var result = JSON.parse(xhr.responseText);//json-->js对象



            if(result.code == 200){//自己封装的结果状态码
                document.querySelector(".address_detail").style.display = "block";
                var username = result.data.receiveUsername;
                var userTelno = result.data.receiveUserTelno
                var detailAddress = result.data.addrProvince + result.data.addrCity + result.data.addrArea + result.data.addrStreet + result.data.addrDetail;

                document.querySelector(".receive_username").innerText = username;
                document.querySelector(".receive_telno").innerText = userTelno;
                document.querySelector(".receive_detail_address").innerText = detailAddress;


            }else{
                document.querySelector(".address_no_data_info span").innerText = "暂无数据";
            }

        }else{
            console.log("请求响应失败");
            //json数据不完整可能
        }
    }




}



/**********************2. ajax 异步请求:添加收件地址 *****/
document.querySelector(".saveAddressBtn").onclick= function (){
    var xhr = new XMLHttpRequest();
    var url = "http://localhost:80/app/receiveAddressJson"
    xhr.open("POST",url,true);

    //表单的数据
    var receiveUsername = document.querySelector("#recipientName").value;
    var receiveUserTelno = document.querySelector("#phoneNumber").value;
    var province = document.querySelector("#province").value;
    var city = document.querySelector("#city").value;
    var district = document.querySelector("#district").value;
    var street = document.querySelector("#street").value;
    var address = document.querySelector("#address").value;

    // k1=v1&k2=v2&k3=v3
    var formData = "receiveUserTelno="+receiveUserTelno + "&receiveUsername="+receiveUsername +"&addrProvince="+province+"&addrCity="+city
        +"&addrArea="+district + "&addrStreet="+street+"&addrDetail="+address;
    console.log(formData)
    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xhr.send(formData);  // xhr.send(表单数据)

    xhr.onreadystatechange = function (){
        if(xhr.status ==200 && xhr.readyState ==4) {
            console.log(xhr.responseText);
            let result = JSON.parse(xhr.responseText);
            if (result.code = 200) {
                document.querySelector(".saveMsg").innerText = "添加成功";
            } else {
                document.querySelector(".saveMsg").innerText = "添加失败";
            }
        }
    }
}



ajax_jquery_demo1.js


//根据主键查询
$(".getByIdBtn").click(function (){
    let addressId = 1;
    let url = "http://localhost:80/app/receiveAddressJSon/"+addressId;
    $.get(url,function (result){ // HTTP.status = 200
        console.log(result)
        console.log(result.code ==200)
        if(result.code == 200) {
            //数据渲染到页面
            $(".address_detail").show();
            $(".receive_username").text(result.data.receiveUsername);
            $(".receive_telno").text(result.data.receiveUserTelno);

            var detailAddress = result.data.addrProvince + result.data.addrCity + result.data.addrArea + result.data.addrStreet + result.data.addrDetail;
            $(".receive_detail_address").text(detailAddress);
        }else{
            $(".address_no_data_info").text("暂无数据")
        }
    });
});



//添加
$(".saveAddressBtn").click(function (){
    let url = "http://localhost:80/app/receiveAddressJSon/";
    var formData = $("#addressForm").serialize();  // name1=v1&name2=v2
    console.log(formData)

    $.post(url,formData,function (result){
        console.log(result);
        if(result.code == 200)
            $(".saveMsg").text("添加成功");
        else
            $(".saveMsg").text("添加失败");

    })
})


//3.查询我的所有收件地址(分页)

$(".getMyAllAddressBtn").click(function (){
    getAddressByPage(1);
})


function getAddressByPage(pageNum) {


    var url = "http://localhost:80/app/receiveAddressJSon/page/"+pageNum;

    $.get(url, function (result) {
        console.log(result);
        //1.数据渲染
        let addressArray = result.data.records;
        var ulEle = $("#addressList");
        ulEle.html("");
        $(".page-information").html("");
        for (var i = 0; i < addressArray.length; i++) {

            var addrId = addressArray[i].addrId;
            var username = addressArray[i].receiveUsername;
            var telno = addressArray[i].receiveUserTelno;
            var detailAddress = addressArray[i].addrProvince + addressArray[i].addrCity + addressArray[i].addrArea + addressArray[i].addrStreet + addressArray[i].addrDetail;


            let liElement = '<li>\n' +
                '                    <div class="btn-container">\n' +
                '                        <form class="deleteForm" method="post" action="">\n' +
                '                            <input type="hidden" name="_method" value="DELETE">\n' +
                '                            <input type="hidden" name="addressId" value="' + addrId + '">' +
                '                            <input type="button" value="删除" class="delete-btn">\n' +
                '                            <input type="button" value="修改" class="update-btn">'+
                '                        </form>\n' +
                '                    </div>\n' +
                '                    <h3>' + username + '</h3>\n' +
                '                    <p>手机号: ' + telno + '</p>\n' +
                '                    <p>收件地址: ' + detailAddress + '</p>\n' +
                '                </li>';

            ulEle.append(liElement);

        }


        //2页码渲染
        var pageNum = result.data.current;
        var pages = result.data.pages;
        var total = result.data.total;
        var prePage = result.data.current-1;
        var nextPage = result.data.current+1;


        if(pageNum != 1) //有上一页
            var prePageEle = '<a href="javascript:getAddressByPage('+prePage+')">上一页</a>';
        var pageEle = '  当前是'+pageNum+' 页,共有 '+total+' 条记录,共有 '+pages+'页';
        if(pageNum != pages)//有下一页
            var nextPageEle = '<a href="javascript:getAddressByPage('+nextPage+')">下一页</a>';

        $(".page-information").append(prePageEle).append(pageEle).append(nextPageEle);




    });
}


//4删除收件地址(业务实际是修改status=0)
//事件冒泡,获得删除按钮
$("#addressList").click(function (event){
    var ele = event.target;
    if(ele.nodeName == 'INPUT' && ele.className=='delete-btn'){
        if(window.confirm('你确定要删除这条收件地址记录?')){
            var addressId = ele.previousElementSibling.value;//删除按钮的前一个元素的值
            removeAddress(addressId);
        }
    }
})


//事件冒泡。获得修改按钮
$("#addressList").click(function (event){
    var ele = event.target;
    if(ele.nodeName == 'INPUT' && ele.className=='update-btn'){
        if(window.confirm('你确定要修改这条收件地址记录?')){
            var addressId = ele.previousElementSibling.previousElementSibling.value;//删除按钮的前一个元素的值
            console.log(addressId);
            getUpdatePage(addressId);
        }
    }
})



function removeAddress(addressId){
    $("deleteMsg").text("");
    var url = 'http://localhost:80/app/receiveAddressJSon/'+addressId;


    $.post(url,{_method:'DELETE'},function (result){
        if(result.code == 200){
            $("deleteMsg").text("删除成功");
            getAddressByPage(1);//重新查询列表数据
        }else
            $("deleteMsg").text("删除失败");

        }

    )

}









//渲染修改页面
function getUpdatePage(addressId) {

    var url = "http://localhost:80/app/receiveAddressJSon/"+addressId;

    $.get(url, function (result) {

    //var addressId = $("input[name='addressId']").val();
    //document.getElementsByName("addressId")[0].value;

    var ulEle = $("#addressList");

    ulEle.html("");

        var rd = result.data;
        var addrId = rd.addrId;
        var username = rd.receiveUsername;
        var telno = rd.receiveUserTelno;
        //var detailAddress = rd.addrProvince + rd.addrCity + rd.addrArea + rd.addrStreet + rd.addrDetail;



        let liElement = '<li>\n' +
        '                    <div class="btn-container">\n' +
        '<form id="updateForm" method="post" action="receiveAddressJSon">\n' +
        '        <input type="hidden" name="_method" value="PUT">\n' +
        '        <input type="hidden" name="addrId" value="'+addrId + '">\n' +
        '\n' +
        '        <label for="recipientName">收件人姓名:</label>\n' +
        '        <input type="text" id="recipientName" name="receiveUsername"  value="'+username+'" required>\n' +
        '\n' +
        '        <label for="phoneNumber">收件人手机号:</label>\n' +
        '        <input type="tel" id="phoneNumber" name="receiveUserTelno" value="'+telno+'"   required>\n' +
        '\n' +
        '        <label for="province">省份:</label>\n' +
        '        <select id="province" name="addrProvince" required>\n' +
        '            <option value="'+result.data.addrProvince+'">'+result.data.addrProvince+'</option>\n' +
        '            <option value="北京">北京</option>\n' +
        '            <option value="上海">上海</option>\n' +
        '            <option value="天津">天津</option>\n' +
        '            <option value="重庆">重庆</option>\n' +
        '            <option value="河北">河北</option>\n' +
        '            <option value="河南">河南</option>\n' +
        '            <option value="湖南">湖南</option>\n' +
        '            <option value="湖北">湖北</option>\n' +
        '            <option value="四川">四川</option>\n' +
        '            <option value="广东">广东</option>\n' +
        '        </select>\n' +
        '\n' +
        '        <label for="city">城市:</label>\n' +
        '        <select id="city" name="addrCity" required>\n' +
        '            <option value="'+result.data.addrCity+'">'+result.data.addrCity+'</option>\n' +
        '        </select>\n' +
        '\n' +
        '        <label for="district">区域:</label>\n' +
        '        <input type="text" id="district" name="addrArea" value="'+result.data.addrArea+'" required>\n' +
        '\n' +
        '        <label for="street">街道:</label>\n' +
        '        <input type="text" id="street" name="addrStreet" value="'+result.data.addrStreet+'" required>\n' +
        '\n' +
        '        <label for="address">详细地址:</label>\n' +
        '        <input type="text" id="address" name="addrDetail" value="'+result.data.addrDetail+'" required>\n' +
        '\n' +
        '        <input type="submit" value="修改" class="upbtn" />\n' +
        '    </form>' +
        '                    </div>\n' +
        '                </li>';




    ulEle.append(liElement);



    });


}






//修改
// $(".up-btn").click(function (){
//     let url = "http://localhost:80/app/receiveAddressJSon/";
//     var formData = $("#updateForm").serialize();  // name1=v1&name2=v2
//     console.log(formData)
//
//     $.post(url,formData,{_method:'PUT'},function (result){
//         console.log(result);
//         if(result.code == 200){
//             console.log("成功");
//             getAddressByPage(1);
//         }
//
//
//     })
// })



// $(".upbtn").click(function (){
//     var formData = $("#updateForm").serialize();
//     let url = "http://localhost:80/app/receiveAddressJSon/";
// $.ajax({
//     url: url,
//     type: 'POST', // 发送 POST 请求
//     data: $.extend({}, formData, {_method: 'PUT'}), // 合并 formData 和 _method 字段
//     success: function(result) {
//         console.log(result);
//         if (result.code == 200) {
//             console.log("成功");
//             getAddressByPage(1);
//         }
//     }
// });
// });







































转载请注明出处或者链接地址:https://www.qianduange.cn//article/5659.html
标签
mybatis-plus
评论
发布的文章

CSS(8)空间转换 动画

2024-04-29 12:04:29

CSS介绍(4)--背景属性

2024-04-29 12:04:26

Web学习记录---CSS(1)

2024-04-29 12:04:17

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!