In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly talks about "how to achieve springboot exception and redirection". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to achieve springboot exception and redirection.
Springboot exception and redirection
In spring, there are two types of redirection:
301, permanent jump
302, temporary jump
302 is called by default.
1. Let's use a simple example to redirect the page @ RequestMapping ("/ redirect/ [code]") public RedirectView redirectView (@ PathVariable ("code") int code, HttpSession session) {RedirectView red = new RedirectView ("/", true) / / determine whether it is 301 abnormal if (code = 301) {/ / default is 302 transfer, here it is set to permanent transfer red.setStatusCode (HttpStatus.MOVED_PERMANENTLY);} return red;}
Results:
Whether you visit "redirect/301" or "redirect/302", the result will jump to the home page, but one is 301 type and the other is 302 type.
two。 Use a simpler method to redirect @ RequestMapping ("/ redirect/ [code]") public RedirectView redirectView (@ PathVariable ("code") int code, HttpSession session) {/ / this jump is 302jump, telling the request through a redirect prefix that to jump to the home page / / all redirect requests will jump to the home page return "redirect:/";}
Results:
This kind of redirection is done through 302, no matter what the url after "redirect" is, because as soon as the prefix "redirect" is recognized, it will jump to the home page.
3. In the process of redirection, session is used to transmit information 1. The redirect page @ RequestMapping ("/ redirect/ [code]") public String redirectView (@ PathVariable ("code") int code, HttpSession session) {/ / this kind of jump is all 302jump, telling the request through a redirect prefix To jump to the home page / / all redirect requests will jump to the home page / / pass the message through session session.setAttribute ("msg", "Jump from redirect") Return "redirect:/"; 2. Home @ RequestMapping ("/") @ ResponseBody public String index (HttpSession session) {/ / display the redirected session return "Hello World!" + session.getAttribute ("msg") in the home page;}
Results:
No matter what the url after the redirect is, it returns to the home page and displays the corresponding information.
4.admin request exception @ RequestMapping ("/ admin") @ ResponseBody public String admin (@ RequestParam ("key") String key) {/ / if key= "admin" if ("admin" .equals (key)) {return "hello admin";} / / otherwise throw exception throw new IllegalArgumentException ("Key Wrong!");}
Results:
In the case of "key=admin", the corresponding information is returned; when "key! = admin", the error message is returned.
5. Define the exception @ ExceptionHandler () @ ResponseBody public String error (Exception e) {return "error:" + e.getMessage ();}
Results:
It can be seen that when an exception occurs, the content of the exception interface that we define ourselves is different from that in 4.
Unified handling of springboot exceptions
Here we first explain the annotations or classes that need to be used, and sort them out by the way.
@ ExceptionHandler: the annotation is used in the method. The value specifies an exception. When the exception in the controller where the method is located corresponds to the exception of the annotation, the annotation method will be triggered.
Once an exception occurs in the following controller, the exception capture is transferred to the method for handling.
@ RestController@RequestMapping ("user") public class UserController {@ ExceptionHandler (value = Exception.class) public void solveException () {/ / exception handling logic}}
ControllerAdvice: comments are made on the class, and the annotated class is registered in the spring container. There can be three annotations in the class, @ ExceptionHandler,@InitBinder,@ModelAttribute. The only way to annotate the above three annotations under this class is to apply the method to all methods in the program with @ RequesMapping annotations.
Process:
Customize your own exception
Declare the class with @ ControllerAdvice and the method of @ ExceptionHandler, and apply the method of @ ExceptionHandler to all controller.
Declare a return result class
Declare an enumeration class that contains the types of exceptions that may occur
Demo
Custom exception:
@ Data@AllArgsConstructorpublic class MyException extends RuntimeException {private Integer code; private String msg; public MyException (ResultEnum resultEnum) {this.msg = resultEnum.getMsg (); this.code = resultEnum.getCode ();}}
Custom return result:
@ Data@AllArgsConstructor@NoArgsConstructorpublic class Result {private int code; private String msg;}
Enumerated classes:
Public enum ResultEnum {UNKNOW_ERROR (- 1, "unknown error"), USER_ERROR (- 2, "user information error"), SUCCESS (0, "success"); private Integer code; private String msg; ResultEnum (Integer code, String msg) {this.code = code; this.msg = msg;} / / omitting getter and setter}
Tool class:
Public class ResultUtil {public static Result error (Integer code, String msg) {Result result = new Result (); result.setCode (code); result.setMsg (msg); return result;}}
Custom exception catch class:
@ ControllerAdvice@Slf4jpublic class MyExceptionHandler {/ / receives Exception, that is, the method @ ExceptionHandler (value=Exception.class) @ ResponseBody public Result handle (Exception e) {if (e instanceof MyException) {MyException myException = (MyException) e; return ResultUtil.error (myException.getCode (), myException.getMsg ());} else {return ResultUtil.error (- 1, "unknown error") }}}
Controller class:
RestController@RequestMapping ("user") public class UserController {@ GetMapping ("exception") public void catchException () throws Exception {throw new MyException (ResultEnum.USER_ERROR);}}
Process:
We visit the http://localhost:8080/user/exception to access the method, throw our custom exception, and collect the exception information by enumerating the class.
Through the custom exception capture class, to catch the exception and execute the method.
In the method of the exception catch class, the ResultUtil utility class is used to generate the Result object return.
At this point, I believe you have a deeper understanding of "how to achieve springboot exceptions and redirects". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.