我有一个简单的 Spring MVC 应用程序,我想在其中使用 @ControllerAdvice
处理所有未映射的 url。
这是 Controller :
@ControllerAdvice
public class ExceptionHandlerController {
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NoHandlerFoundException.class)
public String handle404() {
return "exceptions/404page";
}
}
仍然,每次都会得到 Whitelabel Error Page。
我尝试使用 RuntimeException.class
、HttpStatus.BAD_REQUEST
并使用 NoHandlerFoundException
扩展类,但没有用。
有什么建议吗?
最佳答案
要使其正常工作,您需要在 DispecherServlet 上设置 throwExceptionIfNoHandlerFound
属性。你可以这样做:
spring.mvc.throwExceptionIfNoHandlerFound=true
在 application.properties
文件中,否则请求将始终被转发到默认的 servlet,并且将永远抛出 NoHandlerFoundException。
问题是,即使使用这种配置,它也不起作用。来自文档:
Note that if org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler is used, then requests will always be forwarded to the default servlet and NoHandlerFoundException would never be thrown in that case.
因为 Spring Boot 默认使用 org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler
,所以您必须使用自己的 WebMvcConfigurer
覆盖它:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
// Do nothing instead of configurer.enable();
}
}
当然,上面的类在你的情况下可能更复杂。
关于java - Spring ControllerAdvice 中未处理 404 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54116245/