一、环境工具
1、前端
工具:VSCode,
vue-cli、mint-ui构建应用,axios前后端交互。
2、后端
工具:myeclipse,
基于springboot框架搭建项目。
二、项目搭建过程
详见springboot+vue前后端分离(1)
二、流程
1、增加:
(1)前端
adduser(){
axios.get("http://localhost:9090/user/add",{params:{name:this.name,password:this.password}})
.then((res)=>{
alert(res.data);
}).catch((erro)=>{alert(erro)});
},
(2)后端
@GetMapping(path="/add")
public @ResponseBody String add(@RequestParam String name,@RequestParam String password){
User n=new User();
n.setName(name);
n.setPassword(password);
userDao.save(n);
return "新增用户成功!";
}
流程:前端向后端相应地址发送参数,——》后端接收参数,并创建一个新的用户保存到数据库——》返回一个成功消息的字符串给前端。
2、删除
(1)前端
deleteuser(uid){
axios.get("http://localhost:9090/user/delete?id="+uid)
.then((res)=>{
alert(res.data);
})
.catch((erro)=>{alert(erro)})
},
(2)后端
//删除
@GetMapping("/delete")
public @ResponseBody String delete(@RequestParam Integer id){
userDao.delete(id);
return "已经删除了此用户";
}
流程:前端函数,传递用户id——》后端根据用户id删除用户——》返回删除消息字符串,在前端弹出。
3、获取
(1)前端
edituser(uid){
axios.get("http://localhost:9090/user/get?id="+uid)
.then((res)=>{this.editusers=res.data})
.catch((erro)=>{alert(erro)})
},
(2)后端
@GetMapping("/get")
public @ResponseBody User get(@RequestParam int id){
return userDao.getOne(id);
}
流程:前端传递用户id——》后端根据id从数据库查询用户,并返回给前端——》前端将用户放到相应对象。
注:后端实体类要加注解@JsonIgnoreProperties({ “handler”,“hibernateLazyInitializer” });控制类要用@RestController。
3、查询
(1)前端
findAll(){
axios.get('http://localhost:9090/user/findAll')
.then((res)=>{
this.users=res.data;
}).catch((erro)=>{
alert(erro)
});
},
(2)后端
@GetMapping(path="/findAll")
public @ResponseBody Iterable<User> findAll(){
Sort sort=new Sort(Sort.Direction.DESC,"id");
return userDao.findAll(sort);
}
流程:前端指明要获取数据的路径,——》后端查询返回用户集合。——》前端将数据放入数组。