SpringBoot + Lombok + MyBatis + Ajax请求 + JSON数据交互,实现单表的增删改查(单页面)Demo(转载)

一、数据库
在这里插入图片描述

二、项目结构
在这里插入图片描述

三、Java代码
1、配置文件 pom.xml、application.properties

<?xml version="1.0" encoding="UTF-8"?>


4.0.0

org.springframework.boot
spring-boot-starter-parent
2.1.15.RELEASE


cn.lemon
demo
0.0.1-SNAPSHOT
demo
Demo project for Spring Boot

<properties>
    <!--指定字符集-->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.1</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.10</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 ## 端口 server.port=8080

##数据源配置
##连接池类型
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
##数据库驱动
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
##数据库
spring.datasource.url=jdbc:mysql://localhost:3306/db_users?useUnicode=true&characterEncoding=utf8
##用户名
spring.datasource.username=root
##密码
spring.datasource.password=root

##MyBatis配置
mybatis.mapper-locations=classpath*:mybatis/*.xml
mybatis.type-aliases-package=cn.lemon.demo.entity

#配置访问静态文件
spring.mvc.static-path-pattern=/static/**

#thymelea模板配置
#默认页面映射路径
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
#热部署文件,页面不产生缓存,及时更新。关闭模板缓存
spring.thymeleaf.cache=false
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2、实体类 User.java

package cn.lemon.demo.entity;

import lombok.Data;

import java.io.Serializable;

@Data
public class User implements Serializable {
private Integer id;
private String name;
private String sex;
private int age;
private String address;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
3、数据访问层 IUserDao.java、映射文件 IUserDao.xml

package cn.lemon.demo.dao;

import cn.lemon.demo.entity.User;

import java.util.List;

public interface IUserDao {
int insertUser(User user);

int deleteUserById(Integer id);

int updateUser(User user);

User selectUserById(Integer id);

List<User> selectAllUser();

List<User> selectAllUserByName(String name);

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

<?xml version="1.0" encoding="UTF-8"?> name, sex, age, address, #{name}, #{sex}, #{age}, #{address}, insert into user () values ();
<!--根据 id 删除语句-->
<delete id="deleteUserById" parameterType="Integer">
    delete from user where id = #{id};
</delete>

<!--修改-->
<!--update 语句注意空格与逗号的使用-->
<update id="updateUser" parameterType="cn.lemon.demo.entity.User">
    UPDATE user
    <set>
        <if test="name != null and name.trim() != ''">
            name = #{name},
        </if>
        <if test="sex != null and sex.trim() != ''">
            sex = #{sex},
        </if>
        <if test="age != null">
            age = #{age},
        </if>
        <if test="address != null and address.trim() != ''">
            address = #{address},
        </if>
    </set>
    WHERE id = #{id}
</update>

<!--根据 id 查询-->
<select id="selectUserById" parameterType="Integer" resultType="cn.lemon.demo.entity.User">
    select * from user where id = #{id}
</select>

<!--查询所有-->
<select id="selectAllUser" resultType="cn.lemon.demo.entity.User">
    select * from user
</select>

<!--根据 name 模糊查询-->
<select id="selectAllUserByName" resultType="cn.lemon.demo.entity.User">
    select * from user where name like '%${name}%'
</select>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 4、业务逻辑层接口 IUserService.java、实现类 UserServiceImpl.java

package cn.lemon.demo.service;

import cn.lemon.demo.entity.User;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public interface IUserService {
int insertUser(User user);

int deleteUserById(Integer id);

int updateUser(User user);

User selectUserById(Integer id);

List<User> selectAllUser();

List<User> selectAllUserByName(String name);

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package cn.lemon.demo.service.impl;

import cn.lemon.demo.dao.IUserDao;
import cn.lemon.demo.entity.User;
import cn.lemon.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements IUserService {
@Autowired
private IUserDao userDao;

@Override
public int insertUser(User user) {
    return userDao.insertUser(user);
}

@Override
public int deleteUserById(Integer id) {
    return userDao.deleteUserById(id);
}

@Override
public int updateUser(User user) {
    return userDao.updateUser(user);
}

@Override
public User selectUserById(Integer id) {
    return userDao.selectUserById(id);
}

@Override
public List<User> selectAllUser() {
    return userDao.selectAllUser();
}

@Override
public List<User> selectAllUserByName(String name) {
    return userDao.selectAllUserByName(name);
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
5、业务逻辑层测试类 UserServiceImplTest.java

package cn.lemon.demo.service.impl;

import cn.lemon.demo.entity.User;
import cn.lemon.demo.service.IUserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static org.junit.Assert.*;

@SpringBootTest
@RunWith(SpringRunner.class)
public class UserServiceImplTest {
@Autowired
private IUserService userService;

@Test
public void insertUser() {
    User user = new User();
    user.setName("汤普森");
    user.setSex("男");
    user.setAge(28);
    user.setAddress("金州勇士");
    userService.insertUser(user);
}

@Test
public void deleteUserById() {
    userService.deleteUserById(8);
}

@Test
public void updateUser() {
    User u = new User();
    u.setId(4);
    u.setSex("男");
    u.setAddress("洛杉矶湖人");
    u.setAge(38);
    u.setName("詹姆斯");
    userService.updateUser(u);
}

@Test
public void selectUserById() {
    User user = userService.selectUserById(7);
    System.out.println(user.getAddress());
}

@Test
public void selectAllUser() {
    List<User> userList = userService.selectAllUser();
    for (User user : userList) {
        System.out.println(user.getName() + user.getAddress());
    }
}

@Test
public void selectAllUserByName() {
    List<User> userList = userService.selectAllUserByName("兰");
    for (User user : userList) {
        System.out.println(user.getName() + user.getAddress());
    }
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
6、控制层 UserController.java

package cn.lemon.demo.controller;

import cn.lemon.demo.entity.User;
import cn.lemon.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService userService;

//跳转页面
@RequestMapping("/")
public String index() {
    return "index";
}

//查询所有
@RequestMapping(value = "/userList", method = RequestMethod.GET)
@ResponseBody
public Object userList() {
    List<User> userList = userService.selectAllUser();
    return userList;
}

//根据 ID 查询用户
@RequestMapping(value = "/findById/{id}", method = RequestMethod.GET)
@ResponseBody
public Object findById(@PathVariable("id") Integer id) {
    return userService.selectUserById(id);
}

//添加用户
@RequestMapping(value = "/add", method = RequestMethod.GET)
@ResponseBody
public Object addUser(@Valid User user) {
    int i = userService.insertUser(user);
    //System.out.println(user.getName() + user.getAddress());
    return user;
}

//根据 ID 删除用户
@DeleteMapping("/delete/{id}")
public void delete(@PathVariable("id") Integer id) {
    userService.deleteUserById(id);
}

//根据 ID 修改用户
@PutMapping("/update/{id}")
@ResponseBody
public Object update(@PathVariable("id") Integer id,
                     @RequestParam("name") String name,
                     @RequestParam("sex") String sex,
                     @RequestParam("age") Integer age,
                     @RequestParam("address") String address) {
    User user = new User();
    user.setId(id);
    user.setName(name);
    user.setAge(age);
    user.setSex(sex);
    user.setAddress(address);
    userService.updateUser(user);
    return user;
}

//根据 name 查询
@RequestMapping(value = "/selectUserByUsername", method = RequestMethod.GET)
@ResponseBody
public Object selectUserByUsername(@RequestParam("name") String name) {
    //System.out.println(name);
    List<User> users = userService.selectAllUserByName(name);
    return users;
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
四、前端代码
1、index.html(需要引入 Jquery)

用户

用户列表

    

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 2、index.js

//查询所有
$(function () {
var tbody = document.getElementById(“tbody”);
$.ajax({
type: “get”,
url: ‘/user/userList’,
contentType: “application/json;charset=utf-8”,
dataType: ‘json’,
async: false,
success: function (data) {
//清空数据
$("#tbody").html(’’);
//追加数据
for (var i = 0; i < data.length; i++) {
$("#tbody").append("" +
“” + data[i].id + “” +
“” + data[i].name + “” +
“” + data[i].sex + “” +
“” + data[i].age + “” +
“” + data[i].address + “” +
“<input type=‘button’ value=‘修改’ οnclick= 'updateUser(” + data[i].id + “)’/>” + “&nbsp” +
“<input type=‘button’ value=‘删除’ οnclick='deleteUser(” + data[i].id + “)’/>” +
“”);
}
},
error: function () {
window.alert(“查询失败”);
}
});
});

//修改用户回显数据
function updateUser(id) {
//var show = document.getElementById(“show”);

$("#hid").text("修改用户");//把用户列表改为修改用户
$("#head").hide();//隐藏
$("#inputId").hide();//隐藏
$.ajax({
    type: "get",
    url: '/user/findById/' + id,
    contentType: "application/json;charset=utf-8",
    dataType: 'json',
    async: false,
    success: function (data) {
        //清空数据
        //$("#tbody").html('');
        //追加数据
        $("#show").append(
            "编号:<input type='text' id='id' name='id' value='" + data.id + "'><br>" +
            "姓名:<input type='text' id='name' name='name' value='" + data.name + "'><br>" +
            "性别:<input type='text' id='sex' name='sex' value='" + data.sex + "'><br>" +
            "年龄:<input type='text' id='age' name='age' value='" + data.age + "'><br>" +
            "地址:<input type='text' id='address' name='address' value='" + data.address + "'><br>" +
            "<input type='button' value='确定修改' οnclick='update(" + data.id + ")'>");
    },
    error: function () {
        window.alert("无法修改");
    }
})

}

//修改用户
function update(id) {
var name = $(“input[name=‘name’]”).val();
var sex = $(“input[name=‘sex’]”).val();
var age = $(“input[name=‘age’]”).val();
var address = $(“input[name=‘address’]”).val();
$.ajax({
url: ‘/user/update/’ + id,
type: “put”,
async: false,
data: {“name”: name, “sex”: sex, “age”: age, “address”: address},
success: function () {
$("#name").val(name);
$("#sex").val(sex);
$("#age").val(age);
$("#address").val(address);
alert(“修改成功”);
window.location.reload();
},
error: function () {
alert(“修改失败”);
}
});
}

//删除用户
function deleteUser(id) {
$.ajax({
type: “delete”,
url: “/user/delete/” + id,
//dataType: JSON,
async: false,
success: function () {
window.location.reload();
alert(“删除成功”);
},
error: function () {
alert(“删除失败”);
}
});
};

//添加用户显示输入框
function insertUser() {
//var show = document.getElementById(“show”);

$("#hid").text("添加用户");//把用户列表改为修改用户
$("#head").hide();//隐藏
$("#inputId").hide();//隐藏
$.ajax({
    success: function () {
        //追加数据
        $("#show").append(
            "姓名:<input type='text' id='name' name='name' value=''><br>" +
            "性别:<input type='text' id='sex' name='sex' value=''><br>" +
            "年龄:<input type='text' id='age' name='age' value=''><br>" +
            "地址:<input type='text' id='address' name='address' value=''><br>" +
            "<input type='button' value='确定添加' οnclick='insertByUser()'>");
    },
    error: function () {
        window.alert("无法添加");
    }
})

}

//添加用户
function insertByUser() {
var name = $(“input[name=‘name’]”).val();
var sex = $(“input[name=‘sex’]”).val();
var age = $(“input[name=‘age’]”).val();
var address = $(“input[name=‘address’]”).val();
$.ajax({
url: ‘/user/add’,
type: “get”,
//dataType: JSON,
data: {“name”: name, “sex”: sex, “age”: age, “address”: address},
success: function () {
window.alert(“添加成功”);
window.location.reload();
},
error: function () {
window.alert(“添加失败”);
}
});
};

//根据 name 模糊查询
function selectByUserName() {
var name = $(“input[id=‘selectByNameInput’]”).val();
$.ajax({
type: “get”,
url: ‘/user/selectUserByUsername’,
contentType: “application/json;charset=utf-8”,
//dataType: ‘json’,
data: {“name”: name},
async: false,
success: function (data) {
//清空数据
$("#tbody").html(’’);
//追加数据
for (var i = 0; i < data.length; i++) {
$("#tbody").append("" +
“” + data[i].id + “” +
“” + data[i].name + “” +
“” + data[i].sex + “” +
“” + data[i].age + “” +
“” + data[i].address + “” +
“<input type=‘button’ value=‘修改’ οnclick= 'updateUser(” + data[i].id + “)’/>” + “&nbsp” +
“<input type=‘button’ value=‘删除’ οnclick='deleteUser(” + data[i].id + “)’/>” +
“”);
}
},
error: function () {
window.alert(“查询失败”);
}
});
}

代码下载

原文链接:https://blog.csdn.net/weixin_43860260/article/details/107370139?utm_medium=distribute.pc_feed.none-task-blog-personrec_tag-11.nonecase&depth_1-utm_source=distribute.pc_feed.none-task-blog-personrec_tag-11.nonecase&request_id=5f1fecef9cc79f6252ce3764

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值