[英]How to handle 404 page not found exception in Spring MVC with java configuration and no Web.xml
我想在我的Spring MVC Web應用程序中處理404頁面未找到異常,我正在使用SPRING 4.2.5.RELEASE
,我已經閱讀了有關此主題的幾個問題,但類似的問題是使用不同的spring java配置。
我有一個全局異常處理程序控制器類,它有我的所有異常,這個類工作正常,但我無法處理404頁面未找到異常。
這是我按照教程學習的方法
1)我創建了一個名為ResourceNotFoundException
的類,它從RuntimeException
擴展而來,我把這個注釋放在了類定義@ResponseStatus(HttpStatus.NOT_FOUND)
像這樣:
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
}
2)我在異常的控制器類中創建了這個方法
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleResourceNotFoundException() {
return "notFoundJSPPage";
}
但是,當我放置一個不存在的URL時,我收到此錯誤“找不到帶HTTP的HTTP請求的映射”
我讀過的問題說我需要啟用Dispatcher的true選項,但由於我的配置與其他問題不同,我沒有Web.xml
所以我無法應用。
這是我的Config.java
@EnableWebMvc
@Configuration
@ComponentScan({"config", "controllers"})
public class ConfigMVC extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/");
}
@Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
這是我的WebInitializer
public class WebInicializar implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(ConfigMVC.class);
ctx.setServletContext(servletContext);
Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
這是我的全局異常處理程序控制器
@ControllerAdvice
public class GlobalExceptionHandlerController {
@ExceptionHandler(value = NullPointerException.class)
public String handleNullPointerException(Exception e) {
System.out.println("A null pointer exception ocurred " + e);
return "nullpointerExceptionPage";
}
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(value = Exception.class)
public String handleAllException(Exception e) {
System.out.println("A unknow Exception Ocurred: " + e);
return "unknowExceptionPage";
}
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleResourceNotFoundException() {
return "notFoundJSPPage";
}
}
我創建的類擴展了Runtime Exception
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException{
}
我通過將此行放在WebApplicationInitializer.class
onStartup
方法中解決了這個問題
這是我添加servlet.setInitParameter("throwExceptionIfNoHandlerFound", "true");
這就是我添加新行的完整方法
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(ConfigMVC.class);
ctx.setServletContext(servletContext);
Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
servlet.setInitParameter("throwExceptionIfNoHandlerFound", "true");
}
然后我在GlobalExceptionHandlerController.class
創建了這個控制器方法
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handle(NoHandlerFoundException ex) {
return "my404Page";
}
這解決了我的問題我刪除了我的GlobalExceptionHandlerController.class
的handleResourceNotFoundException
控制器方法,因為它沒有必要,我也刪除了我創建的異常類ResourceNotFoundException.class
您還可以擴展AbstractAnnotationConfigDispatcherServletInitializer
並覆蓋此方法:
@Override
protected DispatcherServlet createDispatcherServlet(WebApplicationContext servletAppContext) {
final DispatcherServlet dispatcherServlet = (DispatcherServlet) super.createDispatcherServlet(servletAppContext);
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
return dispatcherServlet;
}
或者這一個:
@Override
public void customizeRegistration(ServletRegistration.Dynamic registration) {
registration.setInitParameter("throwExceptionIfNoHandlerFound", "true");
}
最后在你的ControlerAdvice
使用:
@ExceptionHandler(NoHandlerFoundException.class)
public String error404(Exception ex) {
return new ModelAndView("404");
}
我發現zygimantus的答案由於某種原因沒有用,所以如果你也有同樣的問題,那么不要聲明一個“@ExceptionHandler”,而是將其中一個添加到“@Configuration”類中。 我把它放在我的WebMvcConfigurerAdapter中
@Bean
public HandlerExceptionResolver handlerExceptionResolver(){
HandlerExceptionResolver myResolver = new HandlerExceptionResolver(){
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
//return your 404 page
ModelAndView mav = new ModelAndView("404page");
mav.addObject("error", exception);
return mav;
}
};
return myResolver;
}
但請確保您也遵循其余的zygimantus即
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
在任何控制器中添加以下代碼並創建404頁面
@GetMapping("/*")
public String handle() {
return "404";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.