Spring mvc 重定向到非映射方法中的错误页
我一直在寻找一种方法,在一个没有映射/直接请求的方法中重定向到一个错误页面,但是从一个有映射/直接请求的方法调用 例如: //调用方法Spring mvc 重定向到非映射方法中的错误页,spring-mvc,spring-boot,Spring Mvc,Spring Boot,我一直在寻找一种方法,在一个没有映射/直接请求的方法中重定向到一个错误页面,但是从一个有映射/直接请求的方法调用 例如: //调用方法 @GetMapping("/") public String listUploadedFiles() { doSomething(); // redirect if error must happen in side this method! return "uploadForm"; } //方法进行重定向 public void do
@GetMapping("/")
public String listUploadedFiles() {
doSomething(); // redirect if error must happen in side this method!
return "uploadForm";
}
//方法进行重定向
public void doSomething()
{
try {
// try some code here
} catch(Exception e) {
// call a method which redirects to an error page
}
}
上面的方法是从具有映射的方法调用的,我想直接重定向到发生异常的方法中的错误。这在spring boot中可能吗?您可以像在中一样使用
这只适用于这个类。但如果您想使
@ExceptionHandler
适用于多个控制器类,只需创建类并使用@ControllerAdvice
对其进行注释,然后根据此答案将@ExceptionHandler
方法放在其中。谢谢!工作完美
@GetMapping("/")
public String listUploadedFiles() {
doSomething(); // redirect if error must happen in side this method!
return "uploadForm";
}
public void doSomething() {
try {
// try some code here
} catch(Exception e) {
throw new YourException();
}
}
@ExceptionHandler(YourException.class)
public String handleYourException(YourException e) {
return "errorPage";
}