我在前端有一个带角度的弹簧启动应用程序。
我正在使用带有html5模式的ui-router,我希望spring能够在所有未知路由上呈现相同的index.html。
// Works great, but it also overrides all the resources
@RequestMapping
public String index() {
return "index";
}
// Seems do be the same as above, but still overrides the resources
@RequestMapping("/**")
public String index() {
return "index";
}
// Works well but not for subdirectories. since it doesn't map to those
@RequestMapping("/*")
public String index() {
return "index";
}
所以我的问题是如何创建一个回退映射但是可以通过资源?
答案 0 :(得分:4)
我发现最简单的方法是实现自定义404页面。
@Configuration
public class MvcConfig {
@Bean
public EmbeddedServletContainerCustomizer notFoundCustomizer(){
return new NotFoundIndexTemplate();
}
private static class NotFoundIndexTemplate implements EmbeddedServletContainerCustomizer {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/"));
}
}
}
Neil McGuigan建议使用HandlerInterceptor,但我无法理解如何实现。我很高兴看到如何实现这一点,因为使用html5历史推送状态的单页应用程序将需要此行为。我还没有真正找到解决这个问题的最佳方法。
答案 1 :(得分:1)
为web.xml文件中的所有网址定义一个入口点,如下所示:
<error-page>
<error-code>404</error-code>
<location>/Error_404</location>
</error-page>
这将捕获所有404,即找不到页面错误并抛出/Error_404
url,将其捕获到您的控制器中并推送到所需位置。
答案 2 :(得分:1)
您可以在404处理程序中处理所有不匹配的请求。看看this,有几个选项
您可以做的另一件事是覆盖DefaultAnnotationHandlerMapping
,并通过设置defaultHandler
属性来添加一种全能控制器。
public void setDefaultHandler(Object defaultHandler)
设置此处理程序映射的默认处理程序。如果未找到特定映射,则将返回此处理程序。 默认值为null
,表示没有默认处理程序。
答案 3 :(得分:1)
尝试在控制器中使用@ExceptionHandler,根据要处理的异常类更改Exception.class。
@ExceptionHandler(value = {Exception.class})
public String notFoundErrorHandler() {
return "index";
}