【问题标题】:How to add and read a List from Wildfly (v17) server如何从 Wildfly (v17) 服务器添加和读取列表
【发布时间】:2019-08-26 11:01:18
【问题描述】:

我有多个 (10+) 模块,我想添加对 CORS 的支持。我想只允许(Access-Control-Allow-Origin)我们的组织 prod、test、development、127.0.0.1 和 localhost。

我创建了一个 jax rs ContainerResponseFilter 类,如下所示:

@Provider
public class CorsFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {

        String origin = requestContext.getHeaderString("Access-Control-Allow-Origin");

        if(!getAllowedOriginList().contains(origin))
            throw new ForbiddenException("Not allowed.");

        responseContext.getHeaders().add("Access-Control-Allow-Origin", origin);
        responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
        responseContext.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }

    private List<String> getAllowedOriginList() {
        return Arrays.asList(
                "http://localhost:8080",
                "127.0.0.1:8080",
                "111.123.123.22:8080",
                "222.123.123.22:8080",
                "333.123.123.22:8080"
        );
    }
}

问题在于,当您有很多带有此代码的模块并且您需要更新 IP 地址时,您必须进入并更新每个模块中的此过滤器。这对我来说不是一个好选择。我想知道如何将此 IP 地址列表添加到 Wildfly 17 服务器并从每个模块中获取它?最简单的方法是什么?

【问题讨论】:

  • 您可以在 WildFly 的 JNDI 上下文中添加列表。
  • @NikosParaskevopoulos 你有一个关于如何做到这一点的例子吗?

标签: jakarta-ee filter jax-rs wildfly


【解决方案1】:

一个非常简单的解决方案是使用 WildFly 的 JNDI。假设独立操作(虽然域类似),编辑standalone.xml 的命名部分以添加一个简单的绑定:

<subsystem xmlns="urn:jboss:domain:naming:2.0">
    <bindings>
        <simple name="java:global/corsAllowedOriginList" type="java.lang.String"
            value="localhost:8080,127.0.0.1:8080,111.123.123.22:8080,222.123.123.22:8080,333.123.123.22:8080" />
    </bindings>
    <remote-naming/>
</subsystem>

这可以使用以下代码以编程方式读取:

import javax.naming.InitialContext;

InitialContext ic = new InitialContext();
String corsAllowedOriginList = ic.lookup("java:global/corsAllowedOriginList");
// can be converted to array using String.split(",")

将其作为资源注入更简单:

@Resource(lookup = "java:global/corsAllowedOriginList")
private String corsOriginList;

我建议您在每个应用程序的初始化时只读取一次此值并将其缓存。

顺便说一下,WildFly 的管理指南中的“命名子系统配置”部分对此进行了描述,目前为here

【讨论】:

  • 感谢您的回答。我可以在我的 CorsFilter 类中使用@Resource(lookup = "java:global/corsAllowedOriginList") private String corsOriginList; 来获取值吗?
  • 是的,绝对是,这是一个更好的选择(将其添加到答案中)。
  • 谢谢!我不确定@Resource 注释是否可以在仅使用@Provider 注释的类中工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-09
  • 1970-01-01
  • 2022-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多