Table of contents
3. Encapsulation of information transmitted by the front end
4. Encapsulation of paging processing information
Here is my project structure
Configuration layer
The configuration layer mainly performs the interception function of the interface.
package com.example.project.config;
import com.example.project.interceptors.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//登录接口不拦截
registry.addInterceptor(loginInterceptor).excludePathPatterns("/user/login");
}
}
ControllerControl layer
1. Article control layer
package com.example.project.controller;
import com.example.project.pojo.PageBean;
import com.example.project.pojo.Result;
import com.example.project.pojo.Article;
import com.example.project.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/article")
public class ArticleController {
@Autowired
private ArticleService articleService;
//获取所有文章信息
@GetMapping("/list")
public Result<List<Article>> list(){
List<Article> list=articleService.getlist();
return Result.success(list);
}
//添加文章
@PostMapping
public Result add(@RequestBody Article article){
articleService.add(article);
return Result.success();
}
//获取用户上传的文章
@GetMapping("/mylist")
public Result<List<Article>> mylist(){
List<Article> list=articleService.getmylist();
return Result.success(list);
}
//删除用户文章
//删除用户文章
@DeleteMapping("/delete")
public Result<String> delete(@RequestParam int id){
articleService.delete(id);
return Result.success("操作成功");
}
@PostMapping("/update")
public Result<String> update(@RequestBody Article article){
articleService.update(article);
return Result.success("操作成功");
}
@GetMapping("/page")
public Result<PageBean<Article>> selectpage(Integer pageNum, Integer pageSize){
PageBean<Article> data= articleService.selectpage(pageNum,pageSize);
return Result.success(data);
}
//条件分页查询
@GetMapping("/mypage")
public Result<PageBean<Article>> selectmypage(Integer pageNum, Integer pageSize) {
PageBean<Article> data = articleService.getmypage(pageNum, pageSize);
return Result.success(data);
}
}
2. User control layer
package com.example.project.controller;
import com.example.project.pojo.Result;
import com.example.project.pojo.User;
import com.example.project.service.UserService;
import com.example.project.utils.JwtUtils;
import com.example.project.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
@RestController
@Validated
@RequestMapping("/user")
//@Validated //validation spring 提供的校验数据工具 @Pattern(regexp="^\\${}$") 正则表达式
public class UserController {
@Autowired
private UserService userService;
//添加新管理员
@PostMapping("/register")
public Result register(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password,@Pattern(regexp = "^\\S$") String name){
//查询管理员
User u = userService.findbyusername(username);
if (u == null) {
userService.register(username, password,name);
return Result.success();
} else {
return Result.error("用户名已被占用");
}
}
//获取用户信息
@GetMapping ("/userInfo")
public Result<User> userinfo(){
Map<String,Object> map= ThreadLocalUtil.get();
String username =(String) map.get("username");
User u=userService.findbyusername(username);
return Result.success(u);
}
//登录
@PostMapping("/login")
public Result<String>loginIn(@Pattern(regexp = "^\\S{5,16}$")String username, @Pattern(regexp = "^\\S{5,16}$")String password){
User u = userService.findbyusername(username);
if(u==null){
return Result.error("用户名错误");
}
if(password.equals(u.getPassword())){
Map<String,Object> claims=new HashMap<>();
claims.put("id",u.getId());
claims.put("username",u.getUsername());
claims.put("name",u.getName());
String token = JwtUtils.genToken(claims);
return Result.success(token);
}
return Result.error("用户名或密码错误");
}
//更新密码
@PatchMapping("/updatePwd")
public Result updatePwd(@RequestBody Map<String,String> params){
//校验参数
String oldpwd=params.get("old_pwd");
String newpwd=params.get("new_pwd");
String repwd=params.get("re_pwd");
if(!StringUtils.hasLength(oldpwd)||!StringUtils.hasLength(newpwd)||!StringUtils.hasLength(repwd)){
return Result.error("缺少必要参数");
}
//原密码是否正确
Map<String,Object> map=ThreadLocalUtil.get();
User loginUser=userService.findbyusername((String) map.get("username"));
if(!loginUser.getPassword().equals(oldpwd)){
return Result.error("原密码不正确");
}
if(!newpwd.equals(repwd)){
return Result.error("两次填写的新密码不一样");
}
userService.updatePwd(newpwd);
return Result.success();
}
}
Exception control
Encapsulate all exception information into a Result object
package com.example.project.exception;
import com.example.project.pojo.Result;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class MyExceptionHandler {
@ExceptionHandler(Exception.class)
public Result handleException(Exception e){
e.printStackTrace();
return Result.error(StringUtils.hasLength(e.getMessage())?e.getMessage():"操作失败");
}
}
Interceptor
1.jwt token
After the user successfully logs in, a jwt token will be generated as the user's unique identifier and placed in the interface. The backend will intercept the user through the jwt token. jwt token information can be used as a unique identifier of a user. The following is the tool class for jwt token
package com.example.project.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import java.util.Date;
import java.util.Map;
public class JwtUtils {
private static final String key="zut";
//接受业务数据,生成token并返回
public static String genToken(Map<String,Object> claims){
return JWT.create()
.withClaim("claims",claims)
.withExpiresAt(new Date(System.currentTimeMillis()+1000*60*60*12))
.sign(Algorithm.HMAC256(key));
}
//接受token,验证token 返回数据
public static Map<String,Object> parseToken(String token){
return JWT.require(Algorithm.HMAC256(key))
.build()
.verify(token)
.getClaim("claims").asMap();
}
}
2.Interceptor
Mainly used for login interception
package com.example.project.interceptors;
import com.example.project.utils.JwtUtils;
import com.example.project.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import java.util.Map;
@Component
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token= request.getHeader("jwt");
try {
Map<String, Object> claims = JwtUtils.parseToken(token);
//将claims放入threadlocal
ThreadLocalUtil.set(claims);
return true;
}catch (Exception o){
//表示未登录
response.setStatus(401);
return false;
}
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//清空Threadlocal中的数据
ThreadLocalUtil.remove();
}
}
Mapping layer
mapper mapping to prepare for service classes
1. Article mapping
package com.example.project.mapper;
import com.example.project.pojo.Article;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface ArticleMapper {
//查看所有文章
@Select("select * from article")
List<Article> getlist();
//上传文章
@Insert("insert into article(title,content,description,user,userId,createTime,updateTime,area)values (#{title},#{content},#{description},#{user},#{userId},#{createTime},#{updateTime},#{area})")
void add(Article article);
@Select("select * from article where userId=#{userId}")
List<Article> getmylist(int userId);
@Delete("delete from article where id=#{id}")
void delete(int id);
@Update("update article set title = #{title}, description = #{description}, content = #{content}, updateTime = #{updateTime} where id = #{id}")
void update(Article article);
}
2. User information mapping
package com.example.project.mapper;
import com.example.project.pojo.Article;
import com.example.project.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
@Mapper
public interface UserMapper {
//根据用户名查询
@Select("select * from user where username=#{username}")
User findbyusername(String username);
//添加
@Insert("insert into user(username,password,name)values(#{username},#{password},#{name})")
void add(String username, String password, String name);
//查找我的文章
@Update("update user set password=#{newpwd} where id=#{id} ")
void updatePwd(String newpwd, Integer id);
}
object layer
1.Article
package com.example.project.pojo;
import lombok.Data;
import java.time.LocalDate;
@Data
public class Article {
private Integer id; //文章编号
private String title; //标题
private String content; //内容
private String description;
private String user; //发布者
private Integer userId; //发布者Id
private LocalDate createTime; //发出日期
private LocalDate updateTime; //更改日期
private Integer area;
}
2.User
ackage com.example.project.pojo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
@Data
public class User {
@NotNull
private Integer id;// 主键id
private String username;//用户名 5-16长度
@JsonIgnore
private String password;//密码 5-16长度
@NotEmpty
private String name; //姓名
}
3. Encapsulation of information transmitted by the front end
ackage com.example.project.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
//定义一个Result 以Json格式 传递数据给前端
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result <T>{
private Integer code; //状态码 0成功 -1失败
private String mess; //提示信息
private T data;//
public static <E> Result<E> success(E data){
return new Result<>(0,"操作成功",data);
}
public static Result success(){
return new Result(0,"操作成功",null);
}
public static Result error(String message){
return new Result(1,message,null);
}
}
4. Encapsulation of paging processing information
package com.example.project.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@NoArgsConstructor
@Data
@AllArgsConstructor
public class PageBean<T> {
private Long total;
private List<T> items;
}
service layer
Article service layer
package com.example.project.service;
import com.example.project.pojo.Article;
import com.example.project.pojo.PageBean;
import java.util.List;
public interface ArticleService {
List<Article> getlist();
void add(Article article);
List<Article> getmylist();
void delete(int id);
//更新数据
void update(Article article);
//分页查询
PageBean<Article> selectpage(Integer pageNum, Integer pageSize);
//条件分页查询
PageBean<Article> getmypage(Integer pageNum, Integer pageSize);
}
Article implementation layer
package com.example.project.service.impl;
import com.example.project.mapper.ArticleMapper;
import com.example.project.pojo.Article;
import com.example.project.pojo.PageBean;
import com.example.project.service.ArticleService;
import com.example.project.utils.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
@Service
public class ArticleServiceImpl implements ArticleService {
@Autowired
private ArticleMapper articleMapper;
@Override
public List<Article> getlist() {
List<Article> list=articleMapper.getlist();
return list;
}
@Override
public void add(Article article) {
article.setCreateTime(LocalDate.now()); //添加时间
article.setUpdateTime(LocalDate.now());
Map<String,Object> map=ThreadLocalUtil.get();
String name= (String) map.get("name");
int userId=(int)map.get("id");
article.setUser(name);
article.setUserId(userId);
articleMapper.add(article);
}
@Override
public List<Article> getmylist() {
Map<String,Object> map=ThreadLocalUtil.get();
int userId=(int)map.get("id");
List<Article> list= articleMapper.getmylist(userId);
return list;
}
@Override
public void delete(int id) {
articleMapper.delete(id);
}
@Override
public void update(Article article) {
article.setUpdateTime(LocalDate.now());
articleMapper.update(article);
}
@Override
public PageBean<Article> selectpage(Integer pageNum, Integer pageSize) {
PageBean<Article> pb=new PageBean<>();
//开启分页查询 PageHelper
PageHelper.startPage(pageNum,pageSize);
List<Article> as=articleMapper.getlist();
//Page中提供方法,可以获取PageHelper分页查询后 得到的总记录条数和当前页数据
Page<Article> p=(Page<Article>) as;
pb.setTotal(p.getTotal());
pb.setItems(p.getResult());
return pb;
}
@Override
public PageBean<Article> getmypage(Integer pageNum, Integer pageSize) {
PageBean<Article> pb=new PageBean<>();
//开启分页查询 PageHelper
PageHelper.startPage(pageNum,pageSize);
Map<String,Object> map=ThreadLocalUtil.get();
int userId=(int)map.get("id");
List<Article> as=articleMapper.getmylist(userId);
//Page中提供方法,可以获取PageHelper分页查询后 得到的总记录条数和当前页数据
Page<Article> p=(Page<Article>) as;
pb.setTotal(p.getTotal());
pb.setItems(p.getResult());
return pb;
}
User service layer
import com.example.project.pojo.User;
public interface UserService {
//根据用户名查询管理员
User findbyusername(String username);
//添加新的管理员账户
void register(String username, String password, String name);
//更新密码
void updatePwd(String newpwd);
}
User implementation layer
package com.example.project.service.impl;
import com.example.project.mapper.UserMapper;
import com.example.project.pojo.User;
import com.example.project.service.UserService;
import com.example.project.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User findbyusername(String username) {
User u= userMapper.findbyusername(username);
return u;
}
@Override
public void register(String username, String password, String name) {
userMapper.add(username,password,name);
}
@Override
public void updatePwd(String newpwd) {
Map<String,Object> map= ThreadLocalUtil.get();
Integer id=(Integer) map.get("id");
userMapper.updatePwd(newpwd,id);
}
}
Configuration file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>project</name>
<description>project</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<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>3.0.3</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</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>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter-test</artifactId>
<version>3.0.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<image>
<builder>paketobuildpacks/builder-jammy-base:latest</builder>
</image>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
The above is all the backend code, I hope it can help