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
-
Unitree Robotics Founder Wang Xingxing Releases Video Statement: Warning Against Online Misinformation, Protecting Shareholder InterestsDetail
2025-03-02 12:40:18 1
-
The Age of Smart Homes Arrives: Habitat L32 Ushers in an Upgrade to Living ExperienceDetail
2025-02-28 21:16:59 1
-
Alibaba's DAMO Academy Announces Imminent Delivery of XuanTie C930 Processor, Achieving 15/GHz in SPECint2006 BenchmarkDetail
2025-02-28 11:06:08 1
-
China's OTA Platforms: A High-Efficiency Miracle Under Low Commission RatesDetail
2025-02-28 10:38:34 21
-
China Leads in Setting International Standard for Elderly Care Robots, Ushering in a New Era for the Global Silver EconomyDetail
2025-02-28 10:37:23 1
-
Xiaomi SU7 Ultra: The World's Strongest Four-Door Production Car, 10,000 Pre-orders in Two Hours, Price Drop Ignites the Market!Detail
2025-02-28 10:29:25 1
-
Kingdee Qatar Company Established: Empowering Middle Eastern Enterprises' Digital Transformation with Digital Technology, Driving the "National Vision 2030"Detail
2025-02-28 09:56:02 1
- Detail
-
DeepSeek API Price Adjustment: Off-Peak Discounts Reduce Costs, Up to 75% OffDetail
2025-02-27 10:47:53 21
-
Lenovo's Ask Tian AI Computing Platform Receives Major Upgrade, Enabling Single-Machine Deployment of 671B-Parameter DeepSeek-R1 ModelDetail
2025-02-26 15:22:05 1
-
Largest Mesozoic Scorpion Fossil Discovered in China: Jeholialongchengi Fills Fossil GapDetail
2025-02-26 10:35:56 1
-
Haier Smart Home Leads the Globalization of Appliance Services: Unified Standards, Setting a New Benchmark for Digital ServicesDetail
2025-02-25 17:39:01 1
-
Douyin Livestreaming Shops: A New Engine Driving the Digital Transformation of the Real EconomyDetail
2025-02-25 17:38:14 21
-
Zhou Hongyi, founder of 360 Group, and Nano AI Search's New Energy Vehicle Giveaway Event Concludes Successfully, Marking a Step Forward in AI PopularizationDetail
2025-02-24 18:36:23 31
-
Leaked CAD Renderings Reveal iPhone 17 Series: Two-Tone Back and Novel Camera Designs Spark InterestDetail
2025-02-24 17:27:08 1
-
Yadea Unveils the Modern Series: High-Style Design Meets Tenfold Safety, Ushering in a New Era of Women's CommuteDetail
2025-02-24 14:34:28 1
-
IBM's mandatory return-to-office policy sparks controversy: disguised layoffs, unfair to employees?Detail
2025-02-24 14:15:41 1
-
Apple Halts iCloud Advanced Data Protection in UK: A Stand Against Government 'Backdoor' DemandsDetail
2025-02-24 14:10:40 31
-
S&P Global Sustainability Yearbook 2024: Baidu's Inclusion Highlights the Crucial Role of AI GovernanceDetail
2025-02-19 21:08:50 1
-
Ronshen Refrigerators Lead 2024 Offline Market: Full-Scenario Embedded Refrigerators Drive Consumption UpgradeDetail
2025-02-19 19:12:01 11