【发布时间】:2016-01-13 16:21:47
【问题描述】:
我想在 Spring MVC 应用程序中处理未映射的 urls/404 错误我找到了一个示例 Here SO Answer,我基于 Java 的配置并以这种方式尝试过
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "com.app.controller" })
public class ServletConfigurer extends WebMvcConfigurerAdapter {
private Properties errorResolverProperties;
private Properties errorProperties;
/// Here I'm configuring <beans as mentioned in SO Answer
@Bean
public SimpleUrlHandlerMapping simpleUrlHandlerMapping() {
SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping();
errorResolverProperties = new Properties();
errorProperties = new Properties();
errorProperties.put("/**", pageNotFoundController());
errorResolverProperties.put("mappings", errorProperties);
return simpleUrlHandlerMapping;
}
// this is my Controller
@Bean
public PageNotFoundController pageNotFoundController(){
return new PageNotFoundController();
}
@Bean
public TilesConfigurer tilesConfigurer() {
TilesConfigurer tilesConfigurer = new TilesConfigurer();
tilesConfigurer.setDefinitions("/WEB-INF/tiles_xml/tiles.xml");
return tilesConfigurer;
}
}
我的控制器是
@Controller
public class PageNotFoundController {
@ExceptionHandler
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleINFException(PageNotFoundException ex) {
return "error";
}
}
最后是
public class PageNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public PageNotFoundException(String message) {
super(message);
}
}
但它总是显示相同的 Apache 错误页面,而不是自定义/我的错误页面。
更新
public class AppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext rootContext = getWebApplicationContext();
servletContext.addListener(new ContextLoaderListener(rootContext));
servletContext.setInitParameter("defaultHtmlEscape", "true");
// add the dispatcher servlet and map it to /
DispatcherServlet dispatcherServlet = new DispatcherServlet(rootContext);
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
"springDispatcher", dispatcherServlet);
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
private AnnotationConfigWebApplicationContext getWebApplicationContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation("com.app.config");
return context;
}
}
就是这样..
【问题讨论】:
-
请添加您的 web.xml 文件,您是否在 web.xml 文件中定义了错误页面?
-
抱歉,我有基于 Java 的配置 no web.xml.
-
对不起,我现在意识到这个网址可能会有所帮助stackoverflow.com/a/30785549/1577363
标签: java spring spring-mvc