java—如何通过javaconfig在SpringMVC中设置404页

hmtdttj4  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(252)

首先,我设置 throwExceptionIfNoHandlerFo‌​und ,使其可以引发异常

  1. @Override
  2. protected void customizeRegistration(ServletRegistration.Dynamic registration) {
  3. super.customizeRegistration(registration);
  4. logger.info("正在注册服务...");
  5. registration.setInitParameter("enableLoggingRequestDetails", "true");
  6. registration.setInitParameter("throwExceptionIfNoHandlerFo‌​und","true");
  7. }

然后,我写了一封信 ControllerAdvice 并使用 ExceptionHandler 处理异常,但它不起作用。那我该怎么办呢。

  1. @ControllerAdvice
  2. public class ErrorPageHandler {
  3. private final Logger logger = Logger.getLogger(ExceptionHandler.class);
  4. @ExceptionHandler(NoHandlerFoundException.class)
  5. public String error404(NoHandlerFoundException ex){
  6. logger.error(ex.getMessage(),ex.getCause());
  7. return "404";
  8. }
  9. }
jslywgbw

jslywgbw1#

对于spring application.properties配置文件中的spring引导,必须配置以下内容:

  1. spring.mvc.throw-exception-if-no-handler-found=true
  2. spring.resources.add-mappings=false

那就行了。
在我的测试中,exceptionhandler是为超类exception执行的,我返回modelandview对象而不是字符串。但我想您这边的主要问题是,如果找不到处理程序,throw exception的配置就错了。
没有spring引导,您可以直接在中配置它 DispatcherServlet ,如下所示:

  1. ApplicationContext ctx = ... // Get it somehow.
  2. DispatcherServlet dispatcherServlet = (DispatcherServlet) ctx.getBean("dispatcherServlet");
  3. dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);

除此之外,我还必须使用注解 @EnableWebMvc 然后它开始工作了。

相关问题