SpringBoot unified processing: login verification interceptor, exception handling, data format return
AD |
Spring Boot AOP HandlerInterceptor + WebMvcConfigurer @RestControllerAdvice + @ExceptionHandler @ControllerAdvice @ResponseBodyAdvice1. Session Session Spring AOP Spring 1
Spring Boot AOP
- HandlerInterceptor + WebMvcConfigurer
- @RestControllerAdvice + @ExceptionHandler
- @ControllerAdvice @ResponseBodyAdvice
1.
- Session Session
- Spring AOP
- Spring
1.1
@RestController@RequestMapping("/user")public class UserController { @RequestMapping("/a1") public Boolean login (HttpServletRequest request) { // Session HttpSession session = request.getSession(false); if (session != null && session.getAttribute("userinfo") != null) { // return true; } else { // return false; } } @RequestMapping("/a2") public Boolean login2 (HttpServletRequest request) { // Session HttpSession session = request.getSession(false); if (session != null && session.getAttribute("userinfo") != null) { // return true; } else { // return false; } }}
- AOP
1.2 Spring AOP
Spring AOP
@Aspect // @Componentpublic class UserAspect { // Controller @Pointcut("execution(* com.example.springaop.controller..*.*(..))") public void pointcut(){} // @Before("pointcut()") public void doBefore() {} // @Around("pointcut()") public Object doAround(ProceedingJoinPoint joinPoint) { Object obj = null; System.out.println("Around "); try { obj = joinPoint.proceed(); } catch (Throwable e) { e.printStackTrace(); } System.out.println("Around "); return obj; }}
Spring AOP
- HttpSession Request
- aspectJ
1.3 Spring
Spring AOP Spring HandlerInterceptor
1. Spring HandlerInterceptor preHandle
2.
- @Configuration
- WebMvcConfigurer
- addInterceptors
1
/** * @Description: * @Date 2023/2/13 13:06 */@Componentpublic class LoginIntercept implements HandlerInterceptor { // true // false @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 1. HttpSession HttpSession session = request.getSession(false); if (session != null && session.getAttribute("userinfo") != null) { // return true; } // response.sendRedirect("/login.html"); return false; }}
2
- addPathPatterns URL**
- excludePathPatterns URL
URLJS CSS
/** * @Description: * @Date 2023/2/13 13:13 */@Configurationpublic class AppConfig implements WebMvcConfigurer { @Resource private LoginIntercept loginIntercept; @Override public void addInterceptors(InterceptorRegistry registry) {// registry.addInterceptor(new LoginIntercept());//new registry.addInterceptor(loginIntercept). addPathPatterns("/**"). // url excludePathPatterns("/user/login"). // excludePathPatterns("/user/reg"). excludePathPatterns("/login.html"). excludePathPatterns("/reg.html"). excludePathPatterns("/**/*.js"). excludePathPatterns("/**/*.css"). excludePathPatterns("/**/*.png"). excludePathPatterns("/**/*.jpg"); }}
1.4
- session
1.3
1 html
![](/attached/image1/2023/05/23/2b894c704ff9840a4e8d7e604914b8ff.png)
2 controller UserController
@RestController@RequestMapping("/user")public class UserController { @RequestMapping("/login") public boolean login(HttpServletRequest request,String username, String password) { boolean result = false; if (StringUtils.hasLength(username) && StringUtils.hasLength(password)) { if(username.equals("admin") && password.equals("admin")) { HttpSession session = request.getSession(); session.setAttribute("userinfo","userinfo"); return true; } } return result; } @RequestMapping("/index") public String index() { return "Hello Index"; }}
3
![](/attached/image1/2023/05/23/bbdda4468a595e6bedc31671b448acb1.png)
![](/attached/image1/2023/05/23/c8d743811184e892b89d94de127c024c.png)
1.5
Controller
![](/attached/image1/2023/05/23/24004f3206985e73342148dccfd178e6.png)
Controller DispatcherServlet
![](/attached/image1/2023/05/23/af190afad76422ec595a5c11f6422243.png)
DispatcherServlet doDispatch doDispatch
![](/attached/image1/2023/05/23/fa4f13dd93b0210b6d8ec5530032ca7c.png)
Sping
1.6
api c
@Configurationpublic class AppConfig implements WebMvcConfigurer { // api @Override public void configurePathMatch(PathMatchConfigurer configurer) { configurer.addPathPrefix("api", c -> true); }}
![](/attached/image1/2023/05/23/2db24a57f8122ba7cac63f896b720347.png)
2.
@ControllerAdvice
@ExceptionHandler(xxx.class)
@RestController@RequestMapping("/user")public class UserController { @RequestMapping("/index") public String index() { int num = 10/0; return "Hello Index"; }}
config MyExceptionAdvice
@RestControllerAdvice // Controller public class MyExceptionAdvice { @ExceptionHandler(ArithmeticException.class) public HashMap<String,Object> arithmeticExceptionAdvice(ArithmeticException e) { HashMap<String, Object> result = new HashMap<>(); result.put("state",-1); result.put("data",null); result.put("msg" , ""+ e.getMessage()); return result; }}
@ControllerAdvicepublic class MyExceptionAdvice { @ExceptionHandler(ArithmeticException.class) @ResponseBody public HashMap<String,Object> arithmeticExceptionAdvice(ArithmeticException e) { HashMap<String, Object> result = new HashMap<>(); result.put("state",-1); result.put("data",null); result.put("msg" , ""+ e.getMessage()); return result; }}
![](/attached/image1/2023/05/23/99a9a8b0110d0f7a8e3ca3a3f2644a74.png)
@ExceptionHandler(NullPointerException.class)public HashMap<String,Object> nullPointerExceptionAdvice(NullPointerException e) { HashMap<String, Object> result = new HashMap<>(); result.put("state",-1); result.put("data",null); result.put("msg" , ""+ e.getMessage()); return result;}@RequestMapping("/index")public String index(HttpServletRequest request,String username, String password) { Object obj = null; System.out.println(obj.hashCode()); return "Hello Index";}
![](/attached/image1/2023/05/23/d86c8d9802c40835e6d71b23637c3a8f.png)
Exception Exception
@ExceptionHandler(Exception.class)public HashMap<String,Object> exceptionAdvice(Exception e) { HashMap<String, Object> result = new HashMap<>(); result.put("state",-1); result.put("data",null); result.put("msg" , ""+ e.getMessage()); return result;}
![](/attached/image1/2023/05/23/01b17a5b9cd6d42c065351913819e3ca.png)
3.
3.1
1. @ControllerAdvice
2. ResponseBodyAdvice
- supports true
- beforeBodyWrite
@ControllerAdvicepublic class MyResponseAdvice implements ResponseBodyAdvice { // boolean true beforeBodyWrite // false @Override public boolean supports(MethodParameter returnType, Class converterType) { return true; } // @Override public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { HashMap<String,Object> result = new HashMap<>(); result.put("state",1); result.put("data",body); result.put("msg",""); return result; }}@RestController@RequestMapping("/user")public class UserController { @RequestMapping("/login") public boolean login(HttpServletRequest request,String username, String password) { boolean result = false; if (StringUtils.hasLength(username) && StringUtils.hasLength(password)) { if(username.equals("admin") && password.equals("admin")) { HttpSession session = request.getSession(); session.setAttribute("userinfo","userinfo"); return true; } } return result; } @RequestMapping("/reg") public int reg() { return 1; }}
![](/attached/image1/2023/05/23/38730fa8c4ef2350b340ad471042df6f.png)
3.2 @ControllerAdvice
@ControllerAdvice
1 @ControllerAdvice
![](/attached/image1/2023/05/23/635bb74f423a5b39d9264b791b3400e2.png)
@ControllerAdvice @Component InitializingBean
2 initializingBean
Spring MVC RequestMappingHandlerAdapter afterPropertiesSet
![](/attached/image1/2023/05/23/4dbcfb264859eb40ee0f1777276abdff.png)
3 initControllerAdviceCache
![](/attached/image1/2023/05/23/1212b1e7b4c96192e13d9d20745aac05.png)
@ControllerAdvice Advice Advice
Disclaimer: The content of this article is sourced from the internet. The copyright of the text, images, and other materials belongs to the original author. The platform reprints the materials for the purpose of conveying more information. The content of the article is for reference and learning only, and should not be used for commercial purposes. If it infringes on your legitimate rights and interests, please contact us promptly and we will handle it as soon as possible! We respect copyright and are committed to protecting it. Thank you for sharing.(Email:[email protected])
Mobile advertising space rental |
Tag: SpringBoot unified processing login verification interceptor exception handling data
Overview and research status of graphene photodetectors
NextMicrosoft plans to acquire Blizzard for $69 billion, approved globally, but opposed by Sony
Guess you like
-
Hisense Refrigerators: Ignite the European Championship with Technological Power, Leading Chinese Brands to the WorldDetail
2024-06-19 14:55:30 11
-
Tencent Cloud Builds a Full-Stack Domestic Software System to Drive Integration and Innovation Across IndustriesDetail
2024-06-19 14:45:48 11
- Detail
- Detail
- Detail
- Detail
- Detail
- Detail
- Detail
-
iPhone X: A Classic ReimaginedDetail
2024-04-07 22:45:37 31
- Detail
-
Mid-Range Smartphones Take a Bold Step with Extreme BrightnessDetail
2024-04-07 22:36:57 21
-
Is Xiaomi car worth buying? Netizens' comments are polarized. Some people think it's good, and some people think it's a pitfallDetail
2024-04-07 18:48:04 31
-
Ele.me Unveils "AI Business Assistant" to Empower Retail Merchants with Data-Driven Decision-MakingDetail
2024-04-03 19:13:32 11
-
Long Queues and Confrontations at Shanghai Apple Store OpeningDetail
2024-04-02 23:38:42 31
- Detail
- Detail
- Detail
-
How to Protect Your Phone Privacy: A Comprehensive Guide for 2024Detail
2024-03-31 14:47:00 51
-
The woman claimed that Xiaomi's phone exploded when charging in the early morning. Netizens claimed that Xiaomi 14 "gets hot after hitting the king", and Lei Jun personally respondedDetail
2023-11-17 09:16:23 11