我正在尝试在 Spring Controller 中提供静态资源。
我有一个 index.html
文件,应该返回到每个请求。
我的 Controller 是:
@Controller
public class IndexController {
@RequestMapping(value = "/**", method = RequestMethod.GET)
public String index() {
return "index.html";
}
}
我还添加了资源处理程序:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/");
}
但最后我有以下异常(exception):
Circular view path [/index.html]: would dispatch back to the current handler URL [/index.html] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
据我所知,在我的配置中,所有请求都将由我的 Spring Controller 处理。
所以当我请求时,例如http://localhost/someText
,该请求将由我的 Controller 处理,然后我的 Controller 将重定向发送到 //localhost/index.html
,该请求转到 Spring 的 DispatcherServlet
,然后再次重定向到我的 Controller ,这会导致上面的异常。
此外,我已经尝试了一些选项:制作网络过滤器,它将处理我对 /index.html
的请求,不是通过 spring servlet,而是通过默认的请求(在我的情况下是 undertow 的 DefaultServlet
),但这是不可能的,因为我的应用程序没有打包为 war,而我的 index.html
文件位于 /src/java/resources
。
实际上我发现,对我来说主要问题是在 spring 的 DispatcherServlet
处理程序中,我的请求 (//localhost/index.html
) 被检测为我的 Controller ,而不是资源处理程序。
protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
for (HandlerMapping hm : this.handlerMappings) {
if (logger.isTraceEnabled()) {
logger.trace(
"Testing handler map [" + hm + "] in DispatcherServlet with name '" + getServletName() + "'");
}
HandlerExecutionChain handler = hm.getHandler(request);
if (handler != null) {
return handler;
}
}
return null;
}
那么也许有一种方法可以改变HandlerMapping
的顺序,使资源映射具有比端点映射器更高的优先级?
或者是否可以从我的 Controller 中排除对 /index.html
的请求,以便能够使用 spring 资源处理程序来处理它?</p>
最佳答案
我通过以下方式弄清楚了: 我定义了请求,这些请求应该在某些精确的 Controller 中进行处理。 然后我创建了过滤器,它添加到路径中的所有其他请求前缀“/root”。我制作了一个 Controller ,用于处理为我的 index.html 提供服务的所有“/root/**”请求。
所以,基本上,当我请求“/api/someApi”时,它会通过 API 内容发送到我的 Controller 。但是当我请求“/someStuff/”时 - 在过滤器中它变成“/root/someStuff/” - 所以它会转到返回“/index.html”的 Controller 。
关于java - Spring Controller 中的圆形 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37185938/