文章目录
- 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
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;
@RestController
@RequestMapping("/receiveAddressJSon")
public class ReceiveAddressJsonController {
@Autowired
private IReceiveAddressService addressService;
@GetMapping("{addrId}")
public ServerResult getById(@PathVariable("addrId") Integer arrId){
return addressService.getById(arrId);
}
@GetMapping("")
public ServerResult getAll(){
int custId = 1;
return addressService.getAll(custId);
}
@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);
}
@DeleteMapping("/{addrId}")
public ServerResult remove(@PathVariable("addrId") Integer addressId){
return addressService.removeById(addressId);
}
@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;
@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;
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;
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;
@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){
QueryWrapper<ReceiveAddress> wrapper = new QueryWrapper<>();
wrapper.eq("cust_id",customerId).eq("status",1);
List<ReceiveAddress> addressList = addressMapper.selectList(wrapper);
if(addressList == null || addressList.size()==0)
return ServerResult.getFail("暂无收件地址");
return ServerResult.getSuccess(addressList);
}
public ServerResult save(ReceiveAddress receiveAddress){
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);
}
return ServerResult.updateFail(receiveAddress);
}
@Override
public ServerResult removeById(Integer addressId) {
ReceiveAddress address = addressMapper.selectById(addressId);
address.setStatus(0);
address.setVersion(address.getVersion() + 1);
int rows = addressMapper.updateById(address);
if(rows > 0)
return ServerResult.updateSuccess(address);
return ServerResult.updateFail(address);
}
@Override
public ServerResult updateById(ReceiveAddress address) {
int oldVersion = addressMapper.selectById(address.getAddrId()).getVersion();
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) {
QueryWrapper<ReceiveAddress> wrapper = new QueryWrapper<>();
wrapper.eq("cust_id",customerId).eq("status",1);
Page<ReceiveAddress> page = new Page<>(pageNum,3);
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);
}
public static ServerResult updateSuccess(Object data){
return new ServerResult(200,"处理成功",data);
}
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;
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;
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
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/>
</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>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<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(忽略)
document.querySelector(".getByIdBtn").onclick = function (){
var xhr = new XMLHttpRequest();
var url = "http://localhost:80/app/receiveAddressJSon/1"
xhr.open("GET",url,true);
xhr.send(null);
xhr.onreadystatechange = function (){
if(xhr.readyState == 4 && xhr.status == 200){
var result = JSON.parse(xhr.responseText);
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("请求响应失败");
}
}
}
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;
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.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){
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();
console.log(formData)
$.post(url,formData,function (result){
console.log(result);
if(result.code == 200)
$(".saveMsg").text("添加成功");
else
$(".saveMsg").text("添加失败");
})
})
$(".getMyAllAddressBtn").click(function (){
getAddressByPage(1);
})
function getAddressByPage(pageNum) {
var url = "http://localhost:80/app/receiveAddressJSon/page/"+pageNum;
$.get(url, function (result) {
console.log(result);
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);
}
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);
});
}
$("#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 ulEle = $("#addressList");
ulEle.html("");
var rd = result.data;
var addrId = rd.addrId;
var username = rd.receiveUsername;
var telno = rd.receiveUserTelno;
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);
});
}