我已经为由 Spring Boot 应用程序提供服务的 NextJS 应用程序创建了构建。 根页面 / (即index.html)可以正常打开,并且从那里 NextJS 通过其链接处理客户端导航,因此例如从根 / 我可以访问 /user/edit(实际上是 edit.html) .
到现在为止一切都很好。但是现在,如果用户决定重新加载页面,或者尝试通过键入/粘贴链接来打开此页面。 /user/edit 会给出 404,因为 spring 只将其识别为 /user/edit.html。
我已经尝试过了
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//This works totally fine.
registry.addResourceHandler("/**/*.css").addResourceLocations("classpath:static/");
//This has not impact.
registry.addResourceHandler("/**[^.]+$").addResourceLocations("classpath:static/**.html");
}
}
我知道“classpath:static/**.html”解决起来没有多大意义。但如果可以通过这种方法或任何其他方法实现,那将不胜感激。 我只需要修改不是来自 /api 并且没有扩展名的任何内容的请求路径 + '.html'
我不想编写自己的控制器来处理提供静态内容,而且我没有 SSR,所以不想使用 Thymeleaf,除非它是最后一个选项,也不想更改我所有的 NextJS 路由,例如/user/edit.html -> /user/edit/index.html.
我花了很多时间搜索和尝试不同的东西,我相信 Spring 足够开放,可以将其作为我不知道的配置。任何帮助将不胜感激。
提前致谢。
好吧,我想出了一个简单的解决方案。分享以便为其他人节省时间。
您需要 3 个文件。从技术上讲,您可以将第一个两个合并为一个,但只是一个更干净的解决方案。
public abstract class PathForwardHandlerInterceptor implements HandlerInterceptor {
abstract protected String provideAlternative(String path);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
final String alternative = provideAlternative(request.getServletPath());
if (alternative != null) {
request.getRequestDispatcher(alternative).forward(request, response);
return false;
}
return HandlerInterceptor.super.preHandle(request, response, handler);
}
}
public class ExtensionAppendInterceptor extends PathForwardHandlerInterceptor {
@Override
protected String provideAlternative(String path) {
return ("/".equals(path) || path.contains(".")) ? null : path + ".html";
}
}
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ExtensionAppendInterceptor());
}
}
你找到解决方案了吗?因为我仍然面临这个问题。