Java 将上下文路径添加到 Spring Boot 应用程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20405474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add context path to Spring Boot application
提问by CorreyS
I am trying to set a Spring Boot applications context root programmatically. The reason for the context root is we want the app to be accessed from localhost:port/{app_name}
and have all the controller paths append to it.
我正在尝试以编程方式设置 Spring Boot 应用程序上下文根。上下文根的原因是我们希望从中访问应用程序localhost:port/{app_name}
并将所有控制器路径附加到它。
Here is the application configuration file for the web-app.
这是 web 应用程序的应用程序配置文件。
@Configuration
public class ApplicationConfiguration {
Logger logger = LoggerFactory.getLogger(ApplicationConfiguration.class);
@Value("${mainstay.web.port:12378}")
private String port;
@Value("${mainstay.web.context:/mainstay}")
private String context;
private Set<ErrorPage> pageHandlers;
@PostConstruct
private void init(){
pageHandlers = new HashSet<ErrorPage>();
pageHandlers.add(new ErrorPage(HttpStatus.NOT_FOUND,"/notfound.html"));
pageHandlers.add(new ErrorPage(HttpStatus.FORBIDDEN,"/forbidden.html"));
}
@Bean
public EmbeddedServletContainerFactory servletContainer(){
TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
logger.info("Setting custom configuration for Mainstay:");
logger.info("Setting port to {}",port);
logger.info("Setting context to {}",context);
factory.setPort(Integer.valueOf(port));
factory.setContextPath(context);
factory.setErrorPages(pageHandlers);
return factory;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
}
Here is the index controller for the main page.
这是主页的索引控制器。
@Controller
public class IndexController {
Logger logger = LoggerFactory.getLogger(IndexController.class);
@RequestMapping("/")
public String index(Model model){
logger.info("Setting index page title to Mainstay - Web");
model.addAttribute("title","Mainstay - Web");
return "index";
}
}
The new root of the application should be at localhost:12378/mainstay
, but it is still located at localhost:12378
.
应用程序的新根目录应该在localhost:12378/mainstay
,但它仍然位于localhost:12378
。
What am I missing that is causing Spring Boot to not append the context root before the request mapping?
我错过了什么导致 Spring Boot 在请求映射之前没有附加上下文根?
采纳答案by M. Deinum
Why are you trying to roll your own solution. Spring-boot already supports that.
为什么要尝试推出自己的解决方案。Spring-boot 已经支持了。
If you don't already have one, add an application.properties
file to src\main\resources
. In that properties file, add 2 properties:
如果您还没有,请将application.properties
文件添加到src\main\resources
. 在该属性文件中,添加 2 个属性:
server.contextPath=/mainstay
server.port=12378
UPDATE (Spring Boot 2.0)
更新(Spring Boot 2.0)
As of Spring Boot 2.0 (due to the support of both Spring MVC and Spring WebFlux) the contextPath
has been changed to the following:
从 Spring Boot 2.0 开始(由于 Spring MVC 和 Spring WebFlux 的支持)contextPath
已更改为以下内容:
server.servlet.contextPath=/mainstay
You can then remove your configuration for the custom servlet container. If you need to do some post processing on the container you can add a EmbeddedServletContainerCustomizer
implementation to your configuration (for instance to add the error pages).
然后,您可以删除自定义 servlet 容器的配置。如果您需要对容器进行一些后期处理,您可以EmbeddedServletContainerCustomizer
在配置中添加一个实现(例如添加错误页面)。
Basically the properties inside the application.properties
serve as a default you can always override them by using another application.properties
next to the artifact you deliver or by adding JVM parameters (-Dserver.port=6666
).
基本上,内部的属性application.properties
用作默认值,您可以随时通过application.properties
在您交付的工件旁边使用另一个属性或通过添加 JVM 参数 ( -Dserver.port=6666
)来覆盖它们。
See also The Reference Guideespecially the propertiessection.
The class ServerProperties
implements the EmbeddedServletContainerCustomizer
. The default for contextPath
is ""
. In your code sample you are setting the contextPath
directly on the TomcatEmbeddedServletContainerFactory
. Next the ServerProperties
instance will process this instance and reset it from your path to ""
. (This linedoes a null
check but as the default is ""
it always fail and set the context to ""
and thus overriding yours).
该类ServerProperties
实现了EmbeddedServletContainerCustomizer
. 默认为contextPath
IS ""
。在您的代码示例中,您contextPath
直接在TomcatEmbeddedServletContainerFactory
. 接下来,ServerProperties
实例将处理此实例并将其从您的路径重置为""
. (此行进行null
检查,但默认情况下""
它总是失败并将上下文设置为""
并因此覆盖您的)。
回答by Abhishek Shah
If you are using Spring Boot, then you don't have to configure the server properties via Vean initializing.
如果您使用的是 Spring Boot,那么您不必通过 Vean 初始化来配置服务器属性。
Instead, if one functionality is available for basic configuration, then it can be set in a "properties" file called application
, which should reside under src\main\resources
in your application structure. The "properties" file is available in two formats
相反,如果一项功能可用于基本配置,则可以在名为 的“属性”文件中进行设置,该文件application
应位于src\main\resources
您的应用程序结构下。“属性”文件有两种格式
.yml
.properties
.yml
.properties
The way you specify or set the configurations differs from one format to the other.
您指定或设置配置的方式因一种格式而异。
In your specific case, if you decide to use the extension .properties
, then you would have a file called application.properties
under src\main\resources
with the following configuration settings
在特定情况下,如果你决定使用扩展.properties
,那么你将有一个名为application.properties
下src\main\resources
具有以下配置设置
server.port = 8080
server.contextPath = /context-path
OTOH, if you decide to use the .yml
extension (i.e. application.yml
), you would need to set the configurations using the following format (i.e. YAML
):
OTOH,如果您决定使用.yml
扩展名(即application.yml
),则需要使用以下格式(即YAML
)设置配置:
server:
port: 8080
contextPath: /context-path
For more common properties of Spring Boot refer to the link below:
有关 Spring Boot 的更多常见属性,请参阅以下链接:
https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
回答by Sanket
We can set it in the application.properties
as
API_CONTEXT_ROOT=/therootpath
我们可以将其设置application.properties
为
API_CONTEXT_ROOT=/therootpath
And we access it in the Java class as mentioned below
我们在 Java 类中访问它,如下所述
@Value("${API_CONTEXT_ROOT}")
private String contextRoot;
回答by Michael Simons
The correct properties are
正确的属性是
server.servlet.path
to configure the path of the DispatcherServlet
配置DispatcherServlet的路径
and
和
server.servlet.context-path
to configure the path of the applications context below that.
在其下方配置应用程序上下文的路径。
回答by magemello
If you use Spring Boot 2.0.0 use:
如果您使用 Spring Boot 2.0.0,请使用:
server.servlet.context-path
回答by Gondri
server.contextPath=/mainstay
server.contextPath=/mainstay
works for me if i had one war file in JBOSS. Among multiple war files where each contain jboss-web.xml it didn't work. I had to put jboss-web.xml inside WEB-INF directory with content
如果我在 JBOSS 中有一个战争文件,则对我有用。在每个包含 jboss-web.xml 的多个战争文件中,它不起作用。我不得不将 jboss-web.xml 与内容放在 WEB-INF 目录中
<?xml version="1.0" encoding="UTF-8"?>
<jboss-web xmlns="http://www.jboss.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.jboss.com/xml/ns/javaee http://www.jboss.org/j2ee/schema/jboss-web_5_1.xsd">
<context-root>mainstay</context-root>
</jboss-web>
回答by saravanan
context path can be directly integrated to the code but it is not advisable since it cannot be reused so write in the application.properties file server.contextPath=/name of the folder where you placed the code contextPath = name of the folder where you placed the code/ Note:watch the slash carefully.
上下文路径可以直接集成到代码中,但不可取,因为它不能重复使用,所以在 application.properties 文件中写入 server.contextPath=/放置代码的文件夹的名称 contextPath = 放置的文件夹的名称代码/注意:仔细观察斜线。
回答by Piyush Anjikar
In Spring Boot 1.5:
在 Spring Boot 1.5 中:
Add the following property in application.properties
:
在 中添加以下属性application.properties
:
server.context-path=/demo
Note: /demo
is your context path URL.
注意:/demo
是您的上下文路径 URL。
回答by abdel
please note that the "server.context-path" or "server.servlet.context-path" [starting from springboot 2.0.x] properties will only work if you are deploying to an embedded container e.g., embedded tomcat. These properties will have no effect if you are deploying your application as a war to an external tomcat for example.
请注意,“server.context-path”或“server.servlet.context-path”[从 springboot 2.0.x 开始] 属性仅在您部署到嵌入式容器(例如嵌入式 tomcat)时才有效。例如,如果您将应用程序作为战争部署到外部 tomcat,这些属性将不起作用。
see this answer here: https://stackoverflow.com/a/43856300/4449859
在这里看到这个答案:https: //stackoverflow.com/a/43856300/4449859
回答by Ghulam Murtaza
You can do it by adding the port and contextpath easily to add the configuration in [src\main\resources] .properties file and also .yml file
您可以通过轻松添加端口和上下文路径来实现,以在 [src\main\resources] .properties 文件和 .yml 文件中添加配置
application.porperties file configuration
application.porterties 文件配置
server.port = 8084
server.contextPath = /context-path
application.yml file configuration
application.yml 文件配置
server:
port: 8084
contextPath: /context-path
We can also change it programmatically in spring boot.
我们也可以在 spring boot 中以编程方式更改它。
@Component
public class ServerPortCustomizer implements WebServerFactoryCustomizer<EmbeddedServletContainerCustomizer > {
@Override
public void customize(EmbeddedServletContainerCustomizer factory) {
factory.setContextPath("/context-path");
factory.setPort(8084);
}
}
}
We can also add an other way
我们还可以添加其他方式
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {SpringApplication application = new pringApplication(MyApplication.class);
Map<String, Object> map = new HashMap<>();
map.put("server.servlet.context-path", "/context-path");
map.put("server.port", "808");
application.setDefaultProperties(map);
application.run(args);
}
}
using java command spring boot 1.X
使用 java 命令 spring boot 1.X
java -jar my-app.jar --server.contextPath=/spring-boot-app --server.port=8585
using java command spring boot 2.X
使用 java 命令 spring boot 2.X
java -jar my-app.jar --server.servlet.context-path=/spring-boot-app --server.port=8585