Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Methods of SpringBoot2 exception handling and web Native component injection

2025-03-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of "SpringBoot2 exception handling and web native component injection". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "SpringBoot2 exception handling and web native component injection" can help you solve the problem.

1 exception handling

By default,    SpringBoot will provide / error to handle all error requests and return the corresponding information. For the browser client, it will return an error Whitelabel page containing timestamp, status code, error message, custom exception information, the path where the error occurred, and so on. For the machine client (postman, etc.), it will return an JSON data containing the above.

1.1 error page for exception handling

In order to replace the error Whitelabel pages returned by the browser client,    needs to place the custom html pages under the error folder of static resource static or under the error folder of template engine templates. In this case, when an error occurs, SpringBoot sends / error request to automatically parse these pages for rendering. Page parsing rules: first, accurately match the value of the status code with the page name under the error folder. If the exact match cannot be achieved, fuzzy matching will be carried out in such ways as 4xx and 5xx. If there is no match, return to the Whitelabel page.

1.2 accurate capture of exception handling

If    says that the error page is processed according to the status code, accurate capture is captured by the exception class, followed by a series of custom actions. The specific steps are: create an exception handler class and add @ ControllerAdvice annotation to the class to indicate that it is an exception handler and register the component with the container. The @ ExceptionHandler annotation accurately captures the exception class in the parameters, and defines the specific handling operation in the method body.

@ Slf4j@ControllerAdvicepublic class GlobalExceptionHandler {@ ExceptionHandler ({ArithmeticException.class, NullPointerException.class}) public String handleArithException (Exception e) {log.info ("system caught exception Information: {}", e); return "login";}} 1.3 Custom exception handling

   sometimes we need to customize some runtime exceptions in the program, these exceptions will not generate exception status codes like those exceptions, and will not be considered as exceptions even before they are defined and will not affect the normal operation of the program. At this point, we need to customize the exception generation logic, customize the exception class to create a parameter constructor, annotate the class with @ ResponseStatus, and use the annotation parameters to define the exception response code and exception information.

@ ResponseStatus (value = HttpStatus.FORBIDDEN, reason = "too many users") public class UserTooManyException extends RuntimeException {public UserTooManyException () {} public UserTooManyException (String message) {super (message);}}

Exception generation logic:

/ / judging the number of users and throwing a custom exception with too many users if (users.size () > 3) {throw new UserTooManyException ();} 1.4 the underlying exception of the framework for exception handling

In addition to the exceptions defined in the exception class,    also defines some exceptions at the bottom of the spring framework, which are handled by DefaultHandlerExceptionResolver

2 injection of web native components 2.1 servlet components

The    servlet component needs to customize the creation of a servlet class that inherits HttpServlet, declares the intercepted request using the urlPatterns attribute of the @ WebServlet annotation, and then uses @ ServletComponentScan (basePackages = "…") on the main program class. The annotation registers the component scan with the container.

/ / declare intercepted request @ WebServlet (urlPatterns = "/ my") public class MyServlet extends HttpServlet {@ Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.getWriter () .write ("385695");}} 2.2 filter component

The    filter component needs to customize the creation of a filter class to implement the Filter interface and declare the filtered request using the urlPatterns attribute of the @ WebFilter annotation

@ Slf4j@WebFilter (urlPatterns = {"/ css/*", "/ images/*"}) public class MyFilter implements Filter {@ Override public void init (FilterConfig filterConfig) throws ServletException {log.info ("MyFilter initialization …") ;} @ Override public void doFilter (ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {log.info ("the MyFilter method is working …") ; filterChain.doFilter (servletRequest, servletResponse);} @ Override public void destroy () {log.info ("MyFilter destroyed …") ;}} 2.3 listener components

The    listener component needs to customize the creation of a listener class to implement the ServletContextListener interface and use @ WebListener annotations

@ Slf4j@WebListenerpublic class MyServletContextListener implements ServletContextListener {@ Override public void contextInitialized (ServletContextEvent sce) {log.info ("MyServletContextListener listens to the completion of project initialization …") ; @ Override public void contextDestroyed (ServletContextEvent sce) {log.info ("MyServletContextListener eavesdropping project has been destroyed …") ;}}

In addition to registering with annotations, you can also use configuration classes to register the above three components with the container

@ Configurationpublic class MyRegistConfig {@ Bean public ServletRegistrationBean MyServlet () {MyServlet myServlet = new MyServlet (); return new ServletRegistrationBean (myServlet, "/ my", "/ my02");} @ Bean public FilterRegistrationBean myFilter () {MyFilter myFilter = new MyFilter (); FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean (myFilter); filterRegistrationBean.setUrlPatterns (Arrays.asList ("/ my", "/ my02"); return filterRegistrationBean } @ Bean public ServletListenerRegistrationBean myListener () {MyServletContextListener listener = new MyServletContextListener (); return new ServletListenerRegistrationBean (listener);}}

The / my request declared by the    through the servlet component is not intercepted by the spring interceptor, but is directly handled by the tomcat server: there are now two components intercepting the / my request we sent, one is the spring component DispatcherServlet intercepted through the / path, the other is the tomcat's custom MyServlet component intercepted through the / my path. The tomcat server has a rule for handling requests. When multiple servlet components can process the same request, the most matched component is used, that is, the MyServlet component of tomcat handles the request.

That's all for "SpringBoot2 exception handling and web native component injection". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report