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
-
China's Car Imports Remain Sluggish in 2024: 12% Decline, Sharp Drop in New Energy VehiclesDetail
2025-01-22 11:37:25 1
-
China Railway Group Limited (CRGL) officially debunks "speed-up" ticket booking software: Not a shortcut, but a pathway to riskDetail
2025-01-22 11:36:09 1
-
Dago Bio Completes Over $20 Million A+ Round Funding to Accelerate Novel Molecular Glue Drug DevelopmentDetail
2025-01-22 11:34:05 1
-
Rapid Degradation of Global Lake Submerged Vegetation: Satellite Observations Reveal a Critical Period of Ecosystem ShiftDetail
2025-01-22 11:29:03 1
-
Star Ace Capital Group and Abu Dhabi Investment Office Partner to Build a Global Esports Industry BenchmarkDetail
2025-01-22 11:27:50 1
-
Hisense Television Leads the 100-Inch Large-Screen Market in 2024, Achieving an Unparalleled Industry LegacyDetail
2025-01-22 11:12:49 1
-
WeChat Launches "Gifts" Feature: Streamlining Gift-Giving and Powering Social Commerce GrowthDetail
2025-01-21 16:05:45 1
-
Xiao Chen, a Chinese expert, Elected Chair of IEC/TC45: China's Influence in Nuclear Instrumentation and Control Standardization Reaches New HeightsDetail
2025-01-21 15:52:49 1
-
Poland: An Emerging Market for Chinese Cross-border E-commerce, Cainiao Overseas Warehouses Fuel Explosive GrowthDetail
2025-01-21 11:06:16 1
-
The Central Political and Legal Affairs Work Conference Focuses on Autonomous Driving Legislation: Fast-Tracking Industry DevelopmentDetail
2025-01-20 16:41:45 1
-
The SHEIN Foundation Officially Launches: Partnering with ACT to Drive Textile Recycling and Sustainable Development in AfricaDetail
2025-01-20 15:21:39 1
-
BCIGroup Launches New Brand: Qineng Technology, Focusing on Next-Generation Infrastructure ConstructionDetail
2025-01-20 15:00:24 1
-
The Trump administration's potential TikTok ban could trigger a global domino effect: Lessons from the Kaspersky caseDetail
2025-01-20 08:42:29 1
-
China Leads in Developing IEC 63206 International Standard, Driving Global Innovation in Industrial Process Control System RecordersDetail
2025-01-18 11:06:14 1
-
The 2024 Micro-Short Series Industry Ecological Insight Report: 647,000 Job Opportunities, Rise of Diversified Business Models, and High-Quality Content as the Future TrendDetail
2025-01-17 17:33:01 1
-
Global PC Market Shows Moderate Recovery in 2024: High AIPC Prices a Bottleneck, Huge Growth Potential in 2025Detail
2025-01-17 11:02:09 1
-
Bosch's Smart Cockpit Platform Surpasses 2 Million Units Shipped, Showcasing Strength in Intelligent Driving TechnologyDetail
2025-01-17 10:55:29 1
-
YY Guangzhou Awarded "2024 Network Information Security Support Unit" for Outstanding ContributionsDetail
2025-01-17 10:43:28 1
-
TikTok CEO Invited to Trump's Inauguration, Biden Administration May Delay BanDetail
2025-01-16 20:06:11 1
-
Douyin Denies Opening International Registration: Overseas IPs Don't Equate to Overseas Registration; Platform Actively Combats Account ImpersonationDetail
2025-01-16 14:26:12 1