1.创建一个SpringBoot的项目:
在main下面创建一个文件夹webapp
在webapp下面引入bootstrap的相关文件值引入css和font,不引入js,因为bootstrap中的js是jQUERY写的
在js中引入Vue和axios
2.编写一个用户管理的页面:
引入bootstrap中css的样式
<head>
<meta charset="UTF-8">
<title>用户管理页面</title>
<!--引入bootstrap中css的样式-->
<link rel="stylesheet" href="./bootvue/css/bootstrap.min.css">
</head>
在body中引入Vue js和axios js
<!--引入Vue js-->
<script src="./bootvue/js/vue.js"></script>
<!--引入axios js-->
<script src="./bootvue/js/axios.min.js"></script>
相关的页面的内容可以到bootstrap中查找相应的代码:地址如下
https://v3.bootcss.com/components/
页面的搭建
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户管理页面</title>
<!--引入bootstrap中css的样式-->
<link rel="stylesheet" href="./bootvue/css/bootstrap.min.css">
</head>
<body>
<!--导航-->
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">用户管理系统</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li><a href="#">欢迎进入</a></li>
</ul>
</div>
</div>
</nav>
<div id="app">
<!--中心布局-->
<div class="container-fluid">
<!--搜索框-->
<div class="row">
<div class="col-md-8 col-md-offset-1">
<form class="form-inline">
<div class="form-group">
<label for="searchName">姓名:</label>
<input type="text" class="form-control" v-model="searchName" id="searchName"/>
</div>
<div class="form-group">
<label for="searchEmail">电话号码:</label>
<input type="text" class="form-control" v-model="searchCode" id="searchEmail"/>
</div>
<button type="submit" class="btn btn-info" @click.prevent="searchLike">搜索</button>
</form>
</div>
</div>
<div class="row" style="margin-top: 20px;">
<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>
</table>
</div>
<div class="col-md-4">
<form>
<div class="form-group">
<label for="username">姓名:</label>
<input type="text" class="form-control" id="username" v-model="user.name" placeholder="请输入姓名">
</div>
<div class="form-group">
<label for="age">年龄:</label>
<input type="text" class="form-control" id="age" v-model="user.age" placeholder="请输入密码">
</div>
<div class="form-group">
<label for="salary">薪资:</label>
<input type="text" class="form-control" id="salary" v-model="user.salary" placeholder="请输入工资">
</div>
<div class="form-group">
<label for="phoneCode">电话号码:</label>
<input type="text" class="form-control" id="phoneCode" v-model="user.phoneCode"
placeholder="请输入电话号码">
</div>
<button type="button" class="btn btn-default" @click="saveUserInfo">提交</button>
<button type="button" class="btn btn-danger" @click="restUserInfo">重置</button>
</form>
</div>
</div>
</div>
</div>
<!--引入Vue js-->
<script src="./bootvue/js/vue.js"></script>
<!--引入axios js-->
<script src="./bootvue/js/axios.min.js"></script>
</body>
</html>
将前端页面的数据交给Vue进行管理,创建相应的Vue对象,对数据进行相应的管理和绑定
<script>
const app = new Vue({
el: "#app",
data: {
users: [],//数据赋值应该来源于后端服务接口,在页面加载完成之前完成赋值,created()中
methods: {
}
created() {
//发送查询所有用户信息的操作
axios.get("").then(function (response) {
console.log(response);
}).catch(function (err) {
console.log(err);
});
}
})
</script>
在数据库中创建相应的表:
CREATE table t_user(
id varchar(20) PRIMARY key,
name varchar(20),
age int(3),
salary double(7,2),
phoneCode VARCHAR(20)
);
在main中创建相应的实体,Dao,service,controller
Entity实体类:
package com.lsy.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Accessors(chain=true)
public class User {
private String id;
private String name;
private Integer age;
private Double salary;
private String phoneCode;
}
Dao接口:
package com.lsy.dao;
import com.lsy.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface UserDAO {
//查询所有
List<User> findAll();
//保存用户方法
void save(User user);
}
在resource里面建立Mapper:
UserDaoMapper.xml文件:
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lsy.dao.UserDAO">
<!--保存用户-->
<insert id="save" parameterType="User">
insert into t_user values(#{id},#{name},#{age},#{salary},#{phoneCode})
</insert>
<!--查询所有功能-->
<select id="findAll" resultType="User">
select id,name,age,salary,phoneCode from t_user
</select>
</mapper>
在application.yml文件中进行相应的配置:
server:
port: 8080
servlet:
context-path: /users
spring:
application:
name: users
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password: lsy
mybatis:
mapper-locations: classpath:com/lsy/mapper/*.xml
type-aliases-package: com.lsy.entity
编写相应的测试类,测试Dao层:
package com.lsy;
import com.lsy.dao.UserDAO;
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;
/**
* @Description:
* @Author:lsy
* @Date:
*/
@SpringBootTest(classes = Springboot01Application.class)
@RunWith(SpringRunner.class)
public class TestDao {
@Autowired
private UserDAO userDAO;
@Test
public void testFindAll(){
userDAO.findAll().forEach(user -> System.out.println("user = " + user));
}
}
在service层创建相应的接口还有实现类:
UserService接口
package com.lsy.service;
import com.lsy.entity.User;
import java.util.List;
public interface UserService {
//保存用户
void save(User user);
//查询所有用户
List<User> findAll();
}
UserServiceImpl实现类:
package com.lsy.service;
import com.lsy.dao.UserDAO;
import com.lsy.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.UUID;
@Service
@Transactional //控制事务
public class UserServiceImpl implements UserService {
@Autowired
private UserDAO userDAO;
@Override
public void save(User user) {
user.setId(UUID.randomUUID().toString());
userDAO.save(user);
}
@Override
@Transactional(propagation = Propagation.SUPPORTS)
public List<User> findAll() {
return userDAO.findAll();
}
}
在Controller层编写相应的业务:
package com.lsy.controller;
import com.lsy.entity.User;
import com.lsy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
//保存用户方法
@PostMapping("save")
public Map<String, Object> save(@RequestBody User user) {
Map<String, Object> map = new HashMap<>();
try {
if(StringUtils.isEmpty(user.getId())){
userService.save(user);
}else{
userService.update(user);
}
map.put("success", true);
} catch (Exception e) {
e.printStackTrace();
map.put("success", false);
map.put("message", "用户保存或更新失败!");
}
return map;
}
//查询所有方法
@GetMapping("/findAll")
public List<User> findAll() {
List<User> users = userService.findAll();
return users;
}
}
启动项目之后可以在浏览器输入访问地址:
package com.lsy;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.lsy.dao")
public class Springboot01Application {
public static void main(String[] args) {
SpringApplication.run(Springboot01Application.class, args);
}
}
2.前后端分离之后:
需要在业务层controller层加入跨域的注解:@CrossOrigin
相应的增删改查功能。
package com.lsy.controller;
import com.lsy.entity.User;
import com.lsy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
//模糊搜索方法
@GetMapping("/findLike")
public List<User> findNameOrCode(String name, String code){
return userService.findNameOrPhoneCode(name,code);
}
//查询一个方法
@GetMapping("/findOne")
public User findOne(String id){
return userService.findOne(id);
}
//删除方法
@GetMapping("/delete")
public Map<String, Object> delete(String id) {
Map<String, Object> map = new HashMap<>();
try {
userService.delete(id);
map.put("success",true);
}catch (Exception e){
map.put("success",false);
map.put("message","删除用户失败,请稍后再试!");
}
return map;
}
//保存用户方法
@PostMapping("save")
public Map<String, Object> save(@RequestBody User user) {
Map<String, Object> map = new HashMap<>();
try {
if(StringUtils.isEmpty(user.getId())){
userService.save(user);
}else{
userService.update(user);
}
map.put("success", true);
} catch (Exception e) {
e.printStackTrace();
map.put("success", false);
map.put("message", "用户保存或更新失败!");
}
return map;
}
//查询所有方法
@GetMapping("/findAll")
public List<User> findAll() {
List<User> users = userService.findAll();
return users;
}
}
UserDaoMapper.xml
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lsy.dao.UserDAO">
<!--处理模糊检索-->
<select id="findNameOrPhoneCode" resultType="User">
select id,name,age,salary,phoneCode from t_user
<where>
<if test="name!=''">
name like concat(#{name},'%')
</if>
<if test="code!=''">
or phoneCode like concat('%',#{code},'%')
</if>
</where>
</select>
<!--修改用户信息-->
<update id="update" parameterType="User">
update t_user set name=#{name},age=#{age},salary=#{salary},phoneCode = #{phoneCode}
where id = #{id}
</update>
<!--查询一个人信息-->
<select id="findOne" parameterType="String" resultType="User">
select id,name,age,salary,phoneCode from t_user where id =#{id}
</select>
<!--删除用户信息-->
<delete id="delete" parameterType="String" >
delete from t_user where id = #{id}
</delete>
<!--保存用户-->
<insert id="save" parameterType="User">
insert into t_user values(#{id},#{name},#{age},#{salary},#{phoneCode})
</insert>
<!--查询所有功能-->
<select id="findAll" resultType="User">
select id,name,age,salary,phoneCode from t_user
</select>
</mapper>
UserServiceImpl.java
package com.lsy.service;
import com.lsy.dao.UserDAO;
import com.lsy.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.UUID;
@Service
@Transactional //控制事务
public class UserServiceImpl implements UserService {
@Autowired
private UserDAO userDAO;
@Override
@Transactional(propagation = Propagation.SUPPORTS)
public List<User> findNameOrPhoneCode(String name, String code) {
return userDAO.findNameOrPhoneCode(name,code);
}
@Override
public void update(User user) {
userDAO.update(user);
}
@Override
@Transactional(propagation = Propagation.SUPPORTS)
public User findOne(String id) {
return userDAO.findOne(id);
}
@Override
public void delete(String id) {
userDAO.delete(id);
}
@Override
public void save(User user) {
user.setId(UUID.randomUUID().toString().substring(0,5));
userDAO.save(user);
}
@Override
@Transactional(propagation = Propagation.SUPPORTS)
public List<User> findAll() {
return userDAO.findAll();
}
}
相应的User.html中Vue方法的编写:
<script>
const app = new Vue({
el: "#app",
data: {
users: [],//数据赋值应该来源于后端服务接口,在页面加载完成之前完成赋值,created()中
user: {},//用来完成数据双向绑定,
searchName:"", //用来处理搜索的数据绑定
searchCode:"", //用来处理搜索的数据绑定
},
methods: {
//用来处理模糊检索
searchLike(){
let _this = this;
axios.get("http://localhost:8989/users/user/findLike?name="+this.searchName+"&code="+this.searchCode).then(function (response) {
_this.users = response.data;
});
},
//查询一个人的信息
findOneUserInfo(id){
let _this = this;
//根据id查询一个人信息
axios.get("http://localhost:8989/users/user/findOne?id="+id).then(function (response) {
console.log(response.data);
_this.user = response.data;
});
},
//根据用户id删除用户信息
deleteUserInfo(id) {
let _this = this;
if(window.confirm("确定要删除这条记录吗?")){
//使用axios发送请求根据id删除用户信息
console.log(id);
axios.get("http://localhost:8989/users/user/delete?id=" + id).then(function (response) {
console.log(response.data);
if (response.data.success) {
//更新页面数据
_this.findAll();
} else {
alert(response.data.message);
}
}).catch(function (err) {
console.log(err);
});
}
},
//保存用户信息的函数
saveUserInfo() {
console.log(this.user)
let _this = this;
axios.post('http://localhost:8080/users/user/save', this.user).then(function (response) {
console.log(response.data);
if (response.data.success) {
//更新页面列表
_this.findAll();
//清空上一次保存用户的信息
_this.user = {};
} else {
alert(response.data.message);
}
}).catch(function (err) {
console.log(err);
});
},
//查询所有用户信息的函数
findAll() {
let _this = this;
//发送查询所有用户信息的操作
axios.get("http://localhost:8080/users/user/findAll").then(function (response) {
_this.users = response.data;
}).catch(function (err) {
console.log(err);
});
},
//重置表单数据
restUserInfo() {
this.user = {};
}
},
//生命周期相关函数
created() {
// //在axios中不能直接使用this,因为在axios中this是一个Windows对象。
// let _this=this;
// //发送查询所有用户信息的操作
// axios.get("http://localhost:8080/users/user/findAll").then(function (response) {
// console.log(response.data);
// _this.users=response.data;
// }).catch(function (err) {
// console.log(err);
// });
this.findAll();
}
})
</script>