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
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
1.5
Controller
Controller DispatcherServlet
DispatcherServlet doDispatch doDispatch
Sping
1.6
api c
@Configurationpublic class AppConfig implements WebMvcConfigurer { // api @Override public void configurePathMatch(PathMatchConfigurer configurer) { configurer.addPathPrefix("api", c -> true); }}
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; }}
@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";}
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;}
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; }}
3.2 @ControllerAdvice
@ControllerAdvice
1 @ControllerAdvice
@ControllerAdvice @Component InitializingBean
2 initializingBean
Spring MVC RequestMappingHandlerAdapter afterPropertiesSet
3 initControllerAdviceCache
@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
-
"Macau Story," a mini-series celebrating the 25th anniversary of Macau's return to China, achieves a billion viewsDetail
2024-12-24 16:38:43 1
-
Youku Sports and VICTOR Partner to Deliver an Upgraded and Innovative Live Streaming Experience for the 2024 BWF World Tour FinalsDetail
2024-12-24 14:31:57 1
-
Foxconn's Parent Company, Hon Hai Precision Industry, Invests an Additional RMB 600 Million in its Zhengzhou-based EV Battery UnitDetail
2024-12-24 10:01:13 1
-
2024 Spring Festival Travel Rush New Train Schedule: 321 Additional Trains Nationwide Starting January 5th, Further Enhancing Service Quality and EfficiencyDetail
2024-12-23 12:05:44 1
-
Changan Automobile and EHang Intelligent Sign Strategic Cooperation Agreement to Build Future Flying Car EcosystemDetail
2024-12-22 15:08:38 1
-
Liaoning Province and Baidu Sign Strategic Cooperation Framework Agreement to Jointly Promote AI Industry DevelopmentDetail
2024-12-20 19:36:38 1
-
Wanxun Technology Secures Nearly RMB 200 Million in Funding to Lead Global Soft Robotics Innovation, Set to Showcase Breakthroughs at CES 2025Detail
2024-12-20 15:54:19 1
-
Huolala's 2025 Spring Festival Freight Festival: Supporting Spring Festival Travel, Offering New Year Benefits to Users and DriversDetail
2024-12-20 13:38:20 1
-
The Third Meeting of the Third Council of the International New Energy Solutions Platform (INES): Charting a Blueprint for a "Dual Carbon" FutureDetail
2024-12-19 17:03:07 1
-
WeChat's Official Account Launches "Author Read Aloud Voice" Feature for Personalized Article ListeningDetail
2024-12-18 17:19:57 1
-
The 12th China University Students' Polymer Materials Innovation and Entrepreneurship Competition Finals Grand Opening in Guangrao CountyDetail
2024-12-18 16:04:28 1
-
Tracing the Ancient Shu Road, Winds of the Three Kingdoms: Global Influencer Shu Road Journey LaunchesDetail
2024-12-18 15:23:35 1
-
Seres: A Pioneer in ESG Practices, Driving Sustainable Development of China's New Energy Vehicle IndustryDetail
2024-12-17 16:20:26 1
- Detail
-
My Health, My Guard: Huawei WATCH D2 Aids Precise Blood Pressure Management in the Winter Health BattleDetail
2024-12-17 09:36:15 1
-
Investigation into the Chaos of Airline Seat Selection: Paid Seat Selection, Seat Locking Mechanisms, and Consumer Rights ProtectionDetail
2024-12-15 16:45:48 1
-
Japanese Scientists Grow Human Organs in Pigs: A Balancing Act of Breakthrough and EthicsDetail
2024-12-14 19:48:50 1
-
Pang Donglai and Sam's Club: Two Paths to Transformation in China's Retail IndustryDetail
2024-12-14 17:57:03 1
-
In-Depth Analysis of China's Precision Reducer Industry: Technological Innovation and Market CompetitionDetail
2024-12-14 16:04:26 1
-
Alibaba's "TAO" App Launches in Japan, Targeting High-Quality Service and Convenient LogisticsDetail
2024-12-13 13:22:23 1