自动将根路径重定向到Spring Boot上下文路径 [英] Auto-redirect root path to Spring Boot Context Path
问题描述
我正在使用application.properties文件中指定的Spring Boot上下文路径,并且效果很好
I am using Spring Boot Context Path as specified in the application.properties file, and it works great
server.port=5000
server.context-path=/services
Spring Boot 2.0及更高版本
Spring Boot 2.0 and above
server.port=5000
server.servlet.context-path=/services
但是如何实现根的默认重定向,即"/"到"/services"
But how can we achieve default redirect of root i.e. "/" to "/services"
http://localhost:5000/services -很棒!
但是我希望 http://localhost:5000/自动重定向到->
But I want http://localhost:5000/ to automatically redirect to -> http://localhost:5000/services so that an end user should be able to access the root of the domain and be automatically redirected to the context path
当前访问根节点会抛出404(这对于默认配置是有意义的)
Currently accessing the root is throwing a 404 (which makes sense with the default configuration)
如何实现根目录(即"/")到上下文路径的自动重定向?
How can I achieve the automatic redirect of root i.e. "/" to the context path?
推荐答案
我认为我可以提供解决方案.请参考以下代码.
I think I can provide a solution.Please refer to the following code.
@Configuration
public class RootServletConfig {
@Bean
public TomcatServletWebServerFactory servletWebServerFactory() {
return new TomcatServletWebServerFactory() {
@Override
protected void prepareContext(Host host, ServletContextInitializer[] initializers) {
super.prepareContext(host, initializers);
StandardContext child = new StandardContext();
child.addLifecycleListener(new Tomcat.FixContextListener());
child.setPath("");
ServletContainerInitializer initializer = getServletContextInitializer(getContextPath());
child.addServletContainerInitializer(initializer, Collections.emptySet());
child.setCrossContext(true);
host.addChild(child);
}
};
}
private ServletContainerInitializer getServletContextInitializer(String contextPath) {
return (c, context) -> {
Servlet servlet = new HttpServlet() {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect(contextPath);
}
};
context.addServlet("root", servlet).addMapping("/*");
};
}
}
这篇关于自动将根路径重定向到Spring Boot上下文路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!