每当用户在浏览器中输入错误的网址时,都会导致 NoSuchRequestHandlingMethodException
我想返回一个自定义 View ,而不是 spring 提供的默认 View 。我有 @AdviceController
,其中我尝试通过 @ExceptionHAndler(NoSuchRequestHandlingMethodException.class)
捕获它并返回一个 View ,但它不起作用。我还继承了DefaultHandlerExceptionResolver并覆盖了处理NoSuchRequestHandlingMethodException的方法,这也不起作用。我还尝试通过扩展 SimpleMappingExceptionResolver
setExecptionMapping
(在同一个 @AdviceController
类中)方法将 View 名称注册到异常,但这也不起作用。我不知道我做错了什么。当 spring 在 Controller 中找不到任何映射时,我是否正确地抛出 NoSuchRequestHandlingMethodException
有人可以告诉我如何返回与 HTTP 错误代码匹配的 Spring 异常的自定义 View 。
这是我的@ControllerAdvice
@ControllerAdvice
public class ExceptionHandlerController extends
DefaultHandlerExceptionResolver {
@ExceptionHandler(NoSuchRequestHandlingMethodException.class)
public String handleException(NoSuchRequestHandlingMethodException.class, Model model) {
String error = th.getMessage();
model.addAttribute("error", error);
model.addAttribute(new User());
return "login";
}
@override
protected ModelAndView handleNoSuchRequestHandlingMethodException
(NoSuchRequestHandlingMethodException ex, HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
ModelAndView mav = new ModelAndView("notfound");
return mav;
}
}
更新:解决方案
没有引发 NoSuchRequestHandlingMethodException
的原因是因为 Dispatcher Servlet 将请求委托(delegate)给默认的 servlet 处理程序(在我的例子中 DefaultServletHttpRequestHandler
)并认为它已处理。我实现的解决方法是,我创建了一个带有映射“/*”的处理程序方法,当在任何 Controller 中都没有找到特定映射时执行该方法,并且我通过新的 NoSuchRequestHandlingMethodException
可以在 @ExceptionHandler 中捕获该方法,然后返回自定义 View 。但是,我不知道这样处理异常的缺点。如果有的话请告诉我。
@Controller
public class HomeController {
...
@RequestMapping(value = "/*", method = RequestMethod.GET )
public void handleAtLast(HttpServletRequest request) throws NoSuchRequestHandlingMethodException {
throw new NoSuchRequestHandlingMethodException(request);
}
}
ExceptionHandlerController.java
@ControllerAdvice
public class ExceptionHandlerController extends DefaultHandlerExceptionResolver {
@ExceptionHandler(NoSuchRequestHandlingMethodException.class)
public String handleNoSuchMethodtFoundException(NoSuchRequestHandlingMethodException ex){
return "error/notfound";
}
}
最佳答案
试试这个方法
@ControllerAdvice
public class AppWideExceptionHandler {
@ExceptionHandler(Exception.class) // replace with your exception Class
public String errorHandler(){
System.out.println("caught exception");
return "home"; // your view
}
}
关于java - 在 Spring MVC 中返回 NoSuchRequestHandlingMethodException 404 错误的自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36660532/