Vue+ElementUI实现用户管理前后分离实战二:API接口篇
项目介绍
上一篇介绍了前端相关实现代码和效果,本篇则介绍后端接口API如何实现。 :)
上一篇地址:
https://blog.csdn.net/IndexMan/article/details/112480590
项目截图
用到的技术栈
SpringBoot
Mybatis-Plus
Mysql
实现的API如下
1.登录接口
2.列表接口
3.保存接口
4.删除接口
5.单条查询接口
主要代码
这里主要列一下主要代码片段,完整请看项目源码。
LoginController
@RestController
@RequestMapping("/api")
public class LoginController {
@Autowired
private UserService userService;
@PostMapping("/login")
public Result<String> login(@RequestBody User user, HttpSession session){
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("username",user.getUsername());
wrapper.eq("password",user.getPassword());
User entity = userService.getOne(wrapper);
if (entity == null){
return ResultUtil.fail("用户名密码错误!");
}
else {
session.setAttribute("user",entity);
return ResultUtil.ok("eyJ1aWQiOjUwMCwicmlkIjowLCJpYXQiOjE2MTAzNDg3MjYsImV4cCI6MTYxMDQzNTEyNn0");
}
}
@GetMapping("logout")
public Result<String> logout(HttpServletRequest request){
request.getSession().removeAttribute("user");
return ResultUtil.ok("注销成功");
}
}
UserController
@RestController
@RequestMapping("/api/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/list")
public Result<IPage<User>> list(@RequestParam(required = false) String query,
@RequestParam(defaultValue = "1") Integer pageNo,
@RequestParam(defaultValue = "10") Integer pageSize) {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
if(!StringUtils.isEmpty(query)){
queryWrapper.like("username",query);
}
Page<User> page = new Page<>(pageNo,pageSize);
IPage<User> pageResult = userService.page(page, queryWrapper);
// 设置总记录数
pageResult.setTotal(userService.count(queryWrapper));
return ResultUtil.ok(pageResult);
}
@PostMapping("/removes")
public Result<String> remove(@RequestBody List<Integer> ids){
userService.removeByIds(ids);
return ResultUtil.ok();
}
@PostMapping("/remove/{id}")
public Result<String> remove(@PathVariable Integer id){
userService.removeById(id);
return ResultUtil.ok();
}
@PostMapping("/modify")
public Result<String> save(@RequestBody User entity){
userService.saveOrUpdate(entity);
return ResultUtil.ok();
}
@GetMapping("/{id}")
public Result<User> get(@PathVariable Integer id){
return ResultUtil.ok(userService.getById(id));
}
}
配置跨域
@Configuration
public class CrossConfig implements WebMvcConfigurer{
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT","PATCH")
.maxAge(3600)
.allowedHeaders("*");
}
}
获取源码
喜欢的朋友给我点个赞,谢谢!