我已經開發了使用Wildfly Swarm的REST API,並且我想介紹CORS過濾器,並且我的要求是所有頭/值都應該可以在外部資源中配置。使用Wildfly Swarm的REST API CORSFilter
我已經實現了CORSFilter,但具有硬編碼的標題值,但現在我希望它可以配置爲Production環境。
任何人都可以引導我嗎?
我已經開發了使用Wildfly Swarm的REST API,並且我想介紹CORS過濾器,並且我的要求是所有頭/值都應該可以在外部資源中配置。使用Wildfly Swarm的REST API CORSFilter
我已經實現了CORSFilter,但具有硬編碼的標題值,但現在我希望它可以配置爲Production環境。
任何人都可以引導我嗎?
我使用屬性文件確切地解決了這個問題。
我有以下文件
比我使用maven-antrun-plugin根據選定的maven配置文件使用正確的屬性文件。
<profile>
<id>prod</id>
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<delete file="${project.build.outputDirectory}/cors.properties"/>
<copy file="src/main/resources/cors.prod.properties"
tofile="${project.build.outputDirectory}/cors.properties"/>
<delete file="${project.build.outputDirectory}/cors.stage.properties"/>
<delete file="${project.build.outputDirectory}/cors.prod.properties"/>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
請檢查https://maven.apache.org/guides/mini/guide-building-for-different-environments.html瞭解完整的maven配置。
然後你可以從你的資源加載的屬性,遍歷它們,並添加頁眉
Properties properties = new Properties();
InputStream in = getClass().getClassLoader().getResourceAsStream("cors.properties");
properties.load(in);
in.close();
for (String name : properties.stringPropertyNames()) {
addHeader(name, properties.getProperty(name));
}
您可以使用項目 - <輪廓> .yml更改數值取決於個人資料(如違約,生產,...)。
https://reference.wildfly-swarm.io/v/2017.3.2/configuration.html#_using_yaml
WRT CORSFilter,你可以與@ConfigurationValue的YML注入值。
import org.wildfly.swarm.spi.runtime.annotations.ConfigurationValue;
@ApplicationScoped
@Provider
public class CORSFilter implements ContainerResponseFilter {
@Inject @ConfigurationValue("access-control-max-age")
private int accessControlMaxAge;
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext throws IOException {
responseContext.getHeaders().add(
"Access-Control-Max-Age",
accessControlMaxAge // Injected value
);
// other headers ...
}
}
或者,您可以使用Undertow過濾器而不是使用yml代替CORSFilter。
swarm:
undertow:
filter-configuration:
response-headers:
access-control-max-age:
header-name: Access-Control-Max-Age
header-value: -1
# other headers configuration
servers:
default-server:
hosts:
default-host:
filter-refs:
access-control-max-age:
priority: 1
# other filter refs
我創建了一個例子有兩種方式。
https://github.com/emag-wildfly-swarm-sandbox/wildfly-swarm-cors-filter-demo
我不認爲我們現在有一個辦法設置CORS標頭在我們的項目defaults.yml配置。 你能提出一個問題嗎? https://issues.jboss.org/browse/SWARM – Ken