【发布时间】:2017-06-02 11:07:31
【问题描述】:
我已将我的 EJB 应用程序从 5.0.1 JBOSS 迁移到 JBOSS EAP 7。 我想在我的 EJB 拦截器(或 bean)中检测客户端的 IP 地址
String currentThreadName = Thread.currentThread().getName();
result: default task-16
代码不再有效。如何获取客户端的IP地址?
【问题讨论】:
我已将我的 EJB 应用程序从 5.0.1 JBOSS 迁移到 JBOSS EAP 7。 我想在我的 EJB 拦截器(或 bean)中检测客户端的 IP 地址
String currentThreadName = Thread.currentThread().getName();
result: default task-16
代码不再有效。如何获取客户端的IP地址?
【问题讨论】:
JBoss 社区 wiki 上的这篇文章 [1] 正好解决了您的问题。在 JBoss 5 之前,IP 地址显然必须从工作线程名称中解析出来。这似乎是在早期版本中执行此操作的唯一方法。
private String getCurrentClientIpAddress() {
String currentThreadName = Thread.currentThread().getName();
System.out.println("Threadname: "+currentThreadName);
int begin = currentThreadName.indexOf('[') +1;
int end = currentThreadName.indexOf(']')-1;
String remoteClient = currentThreadName.substring(begin, end);
return remoteClient;
}
[1]https://developer.jboss.org/wiki/HowtogettheClientipaddressinanEJB3Interceptor
【讨论】:
您可以尝试获取远程连接和 IP 地址。我不确定它有多可靠,因为org.jboss.as.security-api 是一个已弃用的模块,可能会在未来的版本中被删除。
然后尝试以下操作:
容器拦截器:
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
import java.net.InetAddress;
import java.security.Principal;
import org.jboss.remoting3.Connection;
import org.jboss.remoting3.security.InetAddressPrincipal;
import org.jboss.as.security.remoting.RemotingContext;
public class ClientIpInterceptor {
@AroundInvoke
private Object iAmAround(final InvocationContext invocationContext) throws Exception {
InetAddress remoteAddr = null;
Connection connection = RemotingContext.getConnection();
for (Principal p : connection.getPrincipals()) {
if (p instanceof InetAddressPrincipal) {
remoteAddr = ((InetAddressPrincipal) p).getInetAddress();
break;
}
}
System.out.println("IP " + remoteAddr);
return invocationContext.proceed();
}
}
jboss-ejb3.xml:
<?xml version="1.0" encoding="UTF-8"?>
<jboss xmlns="http://www.jboss.com/xml/ns/javaee"
xmlns:jee="http://java.sun.com/xml/ns/javaee"
xmlns:ci ="urn:container-interceptors:1.0">
<jee:assembly-descriptor>
<ci:container-interceptors>
<jee:interceptor-binding>
<ejb-name>*</ejb-name>
<interceptor-class>ClientIpInterceptor</interceptor-class>
</jee:interceptor-binding>
</ci:container-interceptors>
</jee:assembly-descriptor>
</jboss>
jboss-deployment-structure.xml:
<?xml version="1.0" encoding="UTF-8"?>
<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.2">
<deployment>
<dependencies>
<module name="org.jboss.remoting3" />
<module name="org.jboss.as.security-api" />
</dependencies>
</deployment>
</jboss-deployment-structure>
【讨论】: