私は私が使用して、すべてのマップされていないURLを処理したいシンプルなSpring MVCのアプリケーションを持っています@ControllerAdvice
。ここでは、コントローラは以下のとおりです。
@ControllerAdvice
public class ExceptionHandlerController {
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NoHandlerFoundException.class)
public String handle404() {
return "exceptions/404page";
}
}
それでも、すべての時間がホワイトレーベルのエラーページを取得します。
私が使用してみましたRuntimeException.class
、HttpStatus.BAD_REQUEST
としてクラス拡張NoHandlerFoundException
が、役に立たないし。
助言がありますか?
それを動作させるためには、設定する必要がありthrowExceptionIfNoHandlerFound
DispecherServletのプロパティ。あなたがそれを行うことができます。
spring.mvc.throwExceptionIfNoHandlerFound=true
でapplication.properties
、ファイル、それ以外の要求は常にデフォルトサーブレットに転送され、NoHandlerFoundExceptionは、これまでにスローされます。
問題は、このような構成であっても、それは動作しません、です。ドキュメントから:
org.springframework.web.servlet.resource.DefaultServletHttpRequestHandlerが使用されている場合、要求は常にデフォルトサーブレットに転送され、NoHandlerFoundExceptionが、その場合にスローされることはありませんことに注意してください。
春ブーツがデフォルトで使用しているので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();
}
}
もちろん、上記のクラスは、より多くのあなたのケースで複雑になるかもしれません。