HOWTO使用通过基于Java的注释配置的Spring MVC全局处理404异常
问题内容:
我正在构建一个Spring 4
MVC应用程序。并且它是使用Java注释完全配置的。没有web.xml
。该应用是使用的实例进行配置的AbstractAnnotationConfigDispatcherServletInitializer
,WebMvcConfigurerAdapter
就像这样,
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.example.*"})
@EnableTransactionManagement
@PropertySource("/WEB-INF/properties/application.properties")
public class WebAppConfig extends WebMvcConfigurerAdapter {
...
}
和
public class WebAppInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
...
}
我现在正在尝试为404页添加全局/全部捕获异常处理程序,HttpStatus.NOT_FOUND
但没有成功。以下是我尝试过的一些方法。
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
@ControllerAdvice
public class GlobalExceptionHandlerController {
@ExceptionHandler
@ResponseStatus(HttpStatus.NOT_FOUND)
public ModelAndView handleException (NoSuchRequestHandlingMethodException ex) {
ModelAndView mav = new ModelAndView();
return mav;
}
@ExceptionHandler
@ResponseStatus(HttpStatus.NOT_FOUND)
public ModelAndView handleExceptiond (NoHandlerFoundException ex) {
ModelAndView mav = new ModelAndView();
return mav;
}
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NoHandlerFoundException.class)
public void handleConflict() {
}
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NoSuchRequestHandlingMethodException.class)
public void handlesdConflict() {
}
}
这些方法均未执行。我不知道如何处理这个问题。我不想使用,web.xml
因为我必须为此创建一个。
问题答案:
默认情况下,DispatcherServlet
不会引发NoHandlerFoundException
。您需要启用它。
本AbstractAnnotationConfigDispatcherServletInitializer
应该让你重写如何DispatcherServlet
被创建。这样做并打电话
DispatcherServlet dispatcherServlet = ...; // might get it from super implementation
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);