Three common instances of SpringBoot unified function processing

Our unified function processing must be processed through Spring interceptors

Spring interceptor 

The implementation of the interceptor is divided into the following two steps:

1. Create a custom interceptor and implement the preHandle (preprocessing before executing specific methods) method of the HandlerInterceptor interface.

2. Add the custom interceptor to the addInterceptors method of WebMvcConfigurer.

Unified Login Processing

If we are using a website, no matter which page you open, as long as the login status fails, you will be re-logged in. We can't put a login operation in each page, which is troublesome, so we use Spring interceptors to Unified Login Processing

1. Custom interceptor

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
 @Override

 public boolean preHandle(HttpServletRequest request, HttpServletRespon
se response, Object handler) throws Exception {
 HttpSession session = request.getSession(false);
 if (session != null && session.getAttribute("userinfo") != null) {
 return true;
 }
 response.setStatus(401);
 return false;
 }
}

There is nothing to say about the rewriting of preHandle, so it is agreed

Then get the session in the request

Here are three parameters of request.getsession

1. No parameters Get the session from the current request. If the session cannot be obtained, a session will be automatically created and the newly created session will be returned. If it is obtained, the obtained session will be returned.

2.true is roughly the same as when there is no parameter

3.false will not automatically create a session when the session cannot be obtained, but will return null

The logic of logging in here is that if you have a session, you don’t need to log in. If you don’t have a session, log in again. If you return to a newly created session, it will be broken.

About returning true means that it can pass (and will be verified by other interceptors) false means interception (it’s dead here, don’t try other interceptors)

Add custom interceptors to system configuration

@Configuration

public class AppConfig implements WebMvcConfigurer {

 @Override

 public void addInterceptors(InterceptorRegistry registry) {
 registry.addInterceptor(new LoginInterceptor())
 .addPathPatterns("/**") 
 .excludePathPatterns("/wuhu");
 }
}

The @Configuration annotation marks this as a component (don't worry, it's a rule anyway)

Add our custom interceptor in registry.addInterceptor. You can also choose not to use new, and you can also perform property injection.

addPathPatterns indicates the URL that needs to be intercepted, and "**" indicates that all methods are intercepted.

excludePathPatterns indicates the URLs that need to be excluded. 

In other words, the actual interception range is all URLs minus /wuhu

Unified exception handling

When we write code, we will always be reminded, oops, this exception needs to be handled, and that exception needs to be handled. The trycatch surrounds the code, which is quite streamlined, and the readability suddenly decreases. If you don’t handle it, it still can’t run. It’s not good to handle it.

So we use this unified exception handling

import java.util.HashMap;
@ControllerAdvice

public class ErrorAdive {
 @ExceptionHandler(Exception.class)
 @ResponseBody

 public Object handler(Exception e) {
 HashMap<String, Object> map = new HashMap<>();
 map.put("state", 0);
 map.put("data", null);
 map.put("msg", e.getMessage());
 return map;
 }
}

Unified exception handling is implemented using @ControllerAdvice + @ExceptionHandler. @ControllerAdvice represents the controller notification class, and @ExceptionHandler is the exception handler. The combination of the two means that a notification is executed when an exception occurs. This unified exception handling You don't need to add it to the system configuration in one step

@ExceptionHandler(Exception.class) This parameter indicates the exception class
 public Object handler(Exception e) This parameter indicates the exception to be intercepted

Then we directly customize a hashmap to put all the data we want to return together and return them together

Uniform data return

We wrote a lot of methods in the development process. When the front-end looks at it, the good guy has a bunch of data. If you understand it, you will chase the back-end (probably you)

That’s basically no good, 80 returns, communicate with you 80 times, so in order to prevent this from happening, directly unify the data return format and just talk about it once (of course, if you have a crush on the front end, then talk about it separately)

import org.springframework.core.MethodParameter;

import org.springframework.http.MediaType;

import org.springframework.http.server.ServerHttpRequest;

import org.springframework.http.server.ServerHttpResponse;

import org.springframework.web.bind.annotation.ControllerAdvice;

import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyA
dvice;

import java.util.HashMap;
@ControllerAdvice

public class ResponseAdvice implements ResponseBodyAdvice {
 /**
 * 内容是否需要重写(通过此⽅法可以选择性部分控制器和⽅法进⾏重写)

 * 返回 true 表示重写

 */

 @Override

 public boolean supports(MethodParameter returnType, Class converterTyp
e) {
 return true;
 }
 /**
 * ⽅法返回之前调⽤此⽅法

 */

 @Override

 public Object beforeBodyWrite(Object body, MethodParameter returnType,
 MediaType selectedContentType,
 Class selectedConverterType, ServerHttpR
equest request,
 ServerHttpResponse response) {
 // 构造统⼀返回对象

 HashMap<String, Object> result = new HashMap<>();
 result.put("state", 1);
 result.put("msg", "");
 result.put("data", body);
 return result;
 }
}

really nothing to say

 HashMap<String, Object> result = new HashMap<>();
 result.put("state", 1);
 result.put("msg", "");
 result.put("data", body);
 return result;

Except for this, it is an agreement, so it is required to write like this

This is the same as above, that is, collect the data in a HashMap and return them together 

Guess you like

Origin blog.csdn.net/chara9885/article/details/130876202