java - 如何在具有java配置且没有Web.xml的Spring MVC中处理404页面未找到异常

标签 java spring spring-mvc exception annotations

我想在我的 Spring MVC 网络应用程序中处理 404 页面未找到异常,我正在使用 SPRING 4.2.5.RELEASE,我已经阅读了几个关于这个主题的问题,但类似的问题是使用不同的 spring java 配置。

我有一个全局异常处理程序 Controller 类,其中包含我的所有异常,此类工作正常,但我无法处理 404 页面未找到异常。

这是我按照教程采取的方法

1) 我创建了一个名为 ResourceNotFoundException 的类,该类扩展自 RuntimeException 并将此注释放在类定义上 @ResponseStatus(HttpStatus.NOT_FOUND)

像这样:

@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException { 

}

2) 我在异常的 Controller 类中创建了这个方法

@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleResourceNotFoundException() {

    return "notFoundJSPPage";
}

但是,当我放置一个不存在的 URL 时,我仍然会收到此错误消息“找不到带有 URI 的 HTTP 请求的映射”

我读过的问题说我需要为 Dispatcher 启用一个选项,但由于我的配置与其他问题不同,而且我没有 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);


    }
}

这是我的全局异常处理程序 Controller

@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";
    }

}

我创建的扩展运行时异常的类

@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException{

}

最佳答案

我通过将这一行放在 WebApplicationInitializer.classonStartup 方法中解决了这个问题

这是我添加的行 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 中创建了这个 Controller 方法

@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handle(NoHandlerFoundException ex) {

  return "my404Page";
}

这解决了我的问题,我删除了 GlobalExceptionHandlerController.class 中的 handleResourceNotFoundException Controller 方法,因为它不是必需的,我还删除了异常类 ResourceNotFoundException .class 我创建的

关于java - 如何在具有java配置且没有Web.xml的Spring MVC中处理404页面未找到异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36000137/

相关文章:

java - 使用 Java 的 Google Admin SDK 用户访问 API

java - 该字符串需要多少份?

java - Spring Boot 与 Groovy 模板——无法迭代 ModelAndView 中的列表

java - 如何在 Spring 的 dispatcherportlet 和 dispatcherservlet 上通过 xml 设置 ThreadContextInheritable(true)

java - org.springframework.web.HttpMediaTypeNotSupportedException : Content type 'application/json' not supported(Ajax, Spring )

spring-mvc - Spring Boot 和 Swagger 2 : UnsatisfiedDependencyException - Repository tests not working

java - 使用 java 在 Rest Assured 中发送 API header

java - Google Drive 公共(public) API 访问

xml - Spring RestTemplate 使用 XML

java - 如何在更新jsp页面中的列表时将两个不同的模型属性映射到jsp中的一张表?