1.数据库准备和js准备
(1)引入vue和axios,下载vue.js和axios.min.js,添加到工程里
(2)application.yml
spring:
datasource:
username: root
password: 111
url: jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8
driver-class-name: com.mysql.cj.jdbc.Driver
server:
port: 8091
mybatis:
configuration:
#开启驼峰命名转换
map-underscore-to-camel-case: true
(3)pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
(4)数据库名为test,表名为t_user
字段有:
private Integer id;
private String username;
private String sex;
private String employeeNum;
private String department;
private String password;
2. 前端页面 userVue.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- 核心 css -->
<link th:href="@{/asserts/css/bootstrap.min.css}" rel="stylesheet">
</head>
<body>
<div class="container">
<div id="app">
<!-- 如果有条件,查询表单ID名必须为condition-form -->
<form id="searchForm">
姓名<input name="username" v-model="name" id="name">
工号<input name="employeeNum" v-model="num" id="num">
<input type="button" value="搜索" @click="searchUser()">
</form>
<!-- 加载bootstraptable的表格,ID名称必须为bootstrap-table -->
<div class="row">
<div class="col-md-8">
<table class="table table-striped table-bordered table-hover">
<tr>
<th>ID</th>
<th>姓名</th>
<th>性别</th>
<th>工号</th>
<th>部门</th>
<th>操作</th>
</tr>
<tbody>
<tr v-for="user,index in users" :key="user.id">
<td>{{user.id}}</td>
<td>{{user.username}}</td>
<td>{{user.sex}}</td>
<td>{{user.employeeNum}}</td>
<td>{{user.department}}</td>
<td>
<button class="btn btn-danger" @click="deleteUser(user.id)">删除</button> <button class="btn btn-primary" @click="findOneUser(user.id)">修改</button>
</td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-4">
<!-- 新增用户的模态框 -->
<form id="addUserForm" method="post" class="form-horizontal">
<div class="form-group">
<label for="inputAccount" class="col-sm-2 control-label">工号</label>
<div class="col-sm-7">
<input type="account" name="employeeNum" v-model="user.employeeNum" class="form-control" id="inputAccount" placeholder="账户"/>
</div>
<label id="errorAccount" for="inputAccount" class="col-sm-3 control-label"></label>
</div>
<div class="form-group">
<label for="inputName" class="col-sm-2 control-label">姓名</label>
<div class="col-sm-7">
<input type="name" name="username" class="col-sm-4 form-control" v-model="user.username" id="inputName" placeholder="姓名"/>
</div>
<label id="errorName" for="inputName" class="col-sm-3 control-label"></label>
</div>
<div class="form-group" >
<label for="inputPassword" class="col-sm-2 control-label">性别</label>
<div class="col-sm-7">
<input type="text" name="sex" class="form-control" id="inputPassword" v-model="user.sex" placeholder="性别"/>
</div>
<label id="errorPassword" for="inputPassword" class="col-sm-3 control-label"></label>
</div>
<div class="form-group">
<label for="inputSex" class="col-sm-2 control-label">部门</label>
<div class="col-sm-7">
<input type="sex" name="department" class="col-sm-4 form-control" v-model="user.department" id="inputSex" placeholder="性别"/>
</div>
<label id="errorSex" for="inputSex" class="col-sm-3 control-label"></label>
</div>
<button type="button" class="btn btn-default" @click="saveUser">提交</button>
<button type="button" class="btn btn-dangeer" @click="resetUser">重置</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="asserts/js/vue.js"></script>
<script src="asserts/js/axios.min.js"></script>
<script>
const app=new Vue({
el: "#app",
data: {
users:[],
user:{},
name:"",
num:""
},
methods:{
searchUser()
{
let _this=this;
console.log(this.user);
axios.get("findLike?name="+this.name+"&num="+this.num).then(function(response){
console.log(response.data);
_this.users=response.data;
}).catch(function(err){
console.log(err);
});
},
//查找用户
findOneUser(id)
{
let _this=this;
console.log(this.user);
axios.get("findVueUser?id="+id).then(function(response){
console.log(response.data);
_this.user=response.data;
}).catch(function(err){
console.log(err);
});
},
//保存用户信息
saveUser(){
let _this=this;
console.log(this.user);
axios.post("addVueUser",this.user).then(function(response){
console.log(response.data);
if(response.data.success)
{
//更新页面列表
_this.findAll();
}
}).catch(function(err){
console.log(err);
});
},
//重置
resetUser(){
this.user={};
},
//查询所有用户信息的函数
findAll(){
let _this=this;
axios.get("getAllUsers").then(function(response){
console.log(response.data);
_this.users=response.data;
}).catch(function(err){
console.log(err);
});
},
//删除用户
deleteUser(id){
let _this=this;
if(window.confirm("确定要删除这条记录吗?")){
axios.get("deleteVueUser?id="+id).then(function(response){
console.log(response.data);
if(response.data.success)
{
//更新页面列表
_this.findAll();
}
}).catch(function(err){
console.log(err);
});
}
}
},
created(){
this.findAll();
}
})
</script>
</body>
</html>
3. 后台controller 层:UserVueController
package com.whale.springboot106.controller;
import com.alibaba.fastjson.JSONObject;
import com.whale.springboot106.bean.User;
import com.whale.springboot106.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@CrossOrigin //可以跨域
public class UserVueController {
@Autowired
UserService userService;
//从前端访问
@RequestMapping("users1")
public String getUserFront1()
{
return "user/userVue";
}
//查找用户
@ResponseBody
@GetMapping("findLike")
public List<User> findNameOrNum(String name,String num){
System.out.println("name==="+name+"num===="+num);
return userService.searchUsers(name,num);
}
//获取所有用户
@ResponseBody
@GetMapping("/getAllUsers")
public List<User> getAllUsers() {
List<User> userList=userService.getALLUsers();
return userList;
}
//保存,新增和修改用同一个方法,判断是通过user是否有id
@ResponseBody
@PostMapping("/addVueUser")
public Map<String,Object> addVueUser(@RequestBody User user)
{
Map<String,Object> map=new HashMap<>();
user.setPassword("1");
try {
if(user.getId()==null) {
System.out.println("addVueUser");
userService.insertUser(user);
}
else {
userService.updateUser(user);
System.out.println("updateVueUser");
}
map.put("success",true);
}catch(Exception e){
map.put("success",false);
map.put("message","用户保存失败!");
}
return map;
}
//删除用户
@ResponseBody
@GetMapping("/deleteVueUser")
public Map<String,Object> deleteVueUser(String id) {
System.out.println("deleteVueUser==="+id);
Map<String,Object> map=new HashMap<>();
try {
userService.deleteById(Integer.parseInt(id));
map.put("success",true);
}catch(Exception e){
map.put("success",false);
map.put("message","删除用户失败,请稍后处理!");
}
return map;
}
//获取用户
@ResponseBody
@GetMapping("/findVueUser")
public User findVueUser(String id) {
System.out.println("findVueUser======"+id);
return userService.getUserById(Integer.parseInt(id));
}
}
4. Serice层:UserService
@Service
public class UserService {
@Autowired
UserMapper userMapper;
public List<User> searchUsers(String name, String num){
List<User> userList=userMapper.searchUsers(name,num);
return userList;
}
public User getUserById(Integer id)
{
return userMapper.getUserById(id);
}
public int insertUser(User user)
{
return userMapper.insertUser(user);
}
public int deleteById(Integer id)
{
return userMapper.deleteById(id);
}
public int updateUser(User user)
{
return userMapper.updateUser(user);
}
public List<User> getALLUsers()
{
return userMapper.getALLUsers();
}
}
5. Mapper层UserMapper
@Mapper
public interface UserMapper {
@Select("select * from t_user where id = #{id}")
public User getUserById(Integer id);
@Options(useGeneratedKeys = true,keyProperty = "id") //加入自增主键
@Insert("insert into t_user(username,sex,employeeNum,department,password) values(#{username},#{sex},#{employeeNum},#{department},#{password})")
public int insertUser(User user);
@Delete("delete from t_user where id=#{id}")
public int deleteById(Integer id);
@Update("update t_user set username=#{username},sex=#{sex},employeeNum=#{employeeNum},department=#{department} where id=#{id}")
public int updateUser(User user);
@Select("select * from t_user order by id desc")
public List<User> getALLUsers();
@Select("select * from t_user where username like CONCAT('%',#{name},'%') and employeeNum like CONCAT('%',#{num},'%')")
public List<User> searchUsers(@Param("name") String name,@Param("num") String num);
}
6. Bean层 User
public class User {
private Integer id;
private String username;
private String sex;
private String employeeNum;
private String department;
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getEmployeeNum() {
return employeeNum;
}
public void setEmployeeNum(String employeeNum) {
this.employeeNum = employeeNum;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
}