SpringBoot unified function processing

Table of contents

SpringBoot unified function processing concept

Unified user login authority verification

Login function code 

Spring interceptor implementation steps:

 Uniform project access prefix

The first method: rewrite the configurePathMatch method for configuration

 The second method: configure in the system configuration file.properties

Unified exception handling returns

Unified data format return


SpringBoot unified function processing concept

SpringBoot unified function processing is the actual combat link of AOP thought, and then we will start to explain SpringBoot unified function actual combat processing.

SpringBoot unified function realization mainly realizes the following functions:

1. Unified user login authority verification (implemented using interceptors)

2. Unified data format return

3. Unified exception handling returns

Unified user login authority verification

        In the original verification of user login authority, it is necessary to verify the login method in each method body, and the code is very troublesome. So the idea of ​​Spring AOP appeared, which can perform unified login authority verification, but the difficulty of implementing unified interception with native Spring AOP lies in:

1. It is very difficult to define the rules (expressions) of interception;

2. It is difficult to get HttpSession in the aspect class.

        So in this context, Spring interceptors appeared.

Login function code 

@RequestMapping("/hi")
@RestController
public class controller {

    @RequestMapping("/getLogin")
    public String Login(){
        System.out.println("执行了login~~");
        return "login~~";
    }

    @RequestMapping("/getUser")
    public String User(){
        System.out.println("执行了user~~");
        return "user~~";
    }

    @RequestMapping("/getReg")
    public String reg(){
        System.out.println("执行了reg~~");
        return "reg~~";
    }

}

Spring interceptor implementation steps:

1. Implement the HandlerInterceptor interface and rewrite the preHeadler method, and write your own business code in the method

public class LoginInter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 用户登录效验
        HttpSession session = request .getSession(false);
        if(session != null && session.getAttribute("userInfo") != null){
            // 说明用户已经登录
            return true;
        }
        // 执行到这里说明用户未登录,既可以设置跳转到登录界面进行重新登录
        response.sendRedirect("/login.html");
        return false;
    }
}

2. Add the interceptor to the configuration file and set the interception rules

        1. Add annotation: @Configuration

        2. Implement the WebMvcConfigurer interface and rewrite the addInterceptors method

        3. Use addPathPatterns to determine which methods need to be intercepted, excludePathPatterns is not to intercept which URLs (** means to intercept all methods)

code show as below

@Configuration
public class config implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInter())
                .addPathPatterns("/**") // 拦截所有请求
                .excludePathPatterns("/hi/getLogin") // 不拦截该请求URL
               .excludePathPatterns("/hi/getReg") // 不拦截该请求URL
                .excludePathPatterns("/**/*.html"); // 不拦截所有的html页面
    }
}

 

 The above code did not intercept the URL as "/hi/getLogin" , "/hi/getReg" , "/**/*.html" , but intercepted the URL as "/hi/getUser", and automatically jumped to the login interface login.html

No interceptor effect

 After adding an interceptor, the corresponding business processing will be performed before calling the Controller. The execution process is as shown in the figure below

 Uniform project access prefix

The first method: rewrite the configurePathMatch method for configuration

 @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.addPathPrefix("hello",c->true);
    }

 

 The second method: configure in the system configuration file.properties

# 配置统一访问前缀
server.servlet.context-path=/hello

 After configuration, if you use the original URL, a 404 error will be reported. At this time, you need to add the prefix /hello to access

 

 

Unified exception handling returns

When an exception occurs in the backend, an exception notification needs to be returned to the frontend, so that the frontend can receive and identify the exception and handle it. Therefore, the backend needs to return a unified exception and submit it to the frontend, otherwise the frontend will not be able to recognize the abnormal error returned by the backend

Example: When a null pointer exception occurs on the backend

  @RequestMapping("/login")
    public String Login(){
        int a = 100/0;
        System.out.println("执行了login~~");
        return "login~~";
    }

 

At this point we need to return a unified exception format json to the front end

step:

1. Create a class and mark @ControllerAdvice on the class

2. Add method @ExceptionHandler to subscribe to exception

@ControllerAdvice represents the controller notification class, and @ExceptionHandler is the exception handler. The combination of the two means that when an exception occurs, a notification is executed and a method event is executed
@ControllerAdvice
@ResponseBody
public class ErrorException {
    @ExceptionHandler(Exception.class)
    public HashMap<String,Object> exception(Exception e){
        HashMap<String,Object> result = new HashMap<>();
        result.put("code","-1"); // 状态码
        result.put("emg",e.getMessage());  // 错误码描述信息
        result.put("data",null);
        return result;
    }

}

The above method means that if an exception occurs, a HashMap object will be returned to the front end, and the fields contained in it are as defined in the code.

Unified data format return

Unified data format return can better facilitate the front-end to receive and analyze the data returned by the back-end, which can greatly speed up work efficiency

step:

1. Add annotations to the class: @ControllerAdvice

2. Implement the interface ResponseBodyAdvice and must rewrite the two methods supports and beforeBodyWrite

@ControllerAdvice
public class Advice implements ResponseBodyAdvice {
    /*
     *重写support和beforeBodyRead两个方法
     * */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;  // 返回true 则执行下面的beforeBodyWrite,否则不执行
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        HashMap<String,Object> map = new HashMap<>(); // 返回数据格式为哈希map格式
        map.put("code",200); // 状态码
        map.put("message","");
        map.put("data",body);
        return map;
    }
}

The data returned by the backend to the frontend is in the form of numbers and strings

The controller code is as follows:

    @RequestMapping("/num")
    public Integer getNum(){
        return new Random().nextInt(100); // 后端传递100以内的随机数字给前端
    }
    @RequestMapping("/char")
    public String getString(){
        return "hello,world"; //后端传递字符串"hello,world"给前端
    }

The back end passes the number to the front end, and the result is displayed normally

 The backend passes the "hello, world" string to the frontend, and the result is displayed incorrectly

Reason: An exception occurs when HashMap is converted into a string, because the string is a special type, and the conversion tool of jakson is needed to convert the HashMap into a string

 Add jaskon code as follows:

if(body instanceof String){ // instanceof 为判断数据类型
            try {
                return objectMapper.writeValueAsString(map); // 将HashMap 转换成字符串类型
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }

 

Run the project again. At this time, the backend will successfully pass the hello and world strings to the frontend.

 

Guess you like

Origin blog.csdn.net/qq_73471456/article/details/131348038