Java:获取客户端信息的Web服务服务器

时间:2017-10-25 15:36:04

标签: java web-services jax-ws

使用一些在线示例(复制/粘贴)我创建了Web服务器和连接到它的客户端。工作正常。客户端发送请求(一切都在同一台PC上运行),服务器响应。现在我试图添加一段代码(在服务器端),标识谁连接并发送请求(基本上获取客户端信息)做了一些研究并找到了代码。我将代码添加到我认为应该去的地方,但是我得到了NullPointerException。我显然缺少一些东西。 下面的代码显示了Web服务方法的实现。我为addPerson方法添加了新的“客户端识别码”。 执行时,客户端调用addPerson和服务器崩溃 HttpExchange exchange =(HttpExchange)msgx.get(“com.sun.xml.ws.http.exchange”);

我知道这很简单(代码在错误的位置?)但我对这个结婚服务概念完全不熟悉。任何帮助将不胜感激。

代码https://www.journaldev.com/9123/jax-ws-tutorial

@WebService(endpointInterface = "tests.PersonService") 

public class PersonServiceImplementation implements PersonService {

    @Resource
    WebServiceContext wsContext; 

    private static Map<Integer,Person> persons = new HashMap<Integer,Person>();

    @Override
    @WebMethod 
    public boolean addPerson(Person p) {
        //// idetify who poked us ////
        MessageContext msgx = wsContext.getMessageContext();
        HttpExchange exchange = (HttpExchange)msgx.get("com.sun.xml.ws.http.exchange");
        InetSocketAddress remoteAddress = exchange.getRemoteAddress();
        String remoteHost = remoteAddress.getHostName(); 
        System.out.println("Who poked us: " +  remoteHost);
        //////////////////////////////
        if(persons.get(p.getId()) != null) return false;
        persons.put(p.getId(), p);
        return true;
    }

    @Override
    public boolean deletePerson(int id) {
        if(persons.get(id) == null) return false;
        persons.remove(id);
        return true;
    }

    @Override
    public Person getPerson(int id) {
        return persons.get(id);
    }

    @Override
    public Person[] getAllPersons() {
        Set<Integer> ids = persons.keySet();
        Person[] p = new Person[ids.size()];
        int i=0;
        for(Integer id : ids){
            p[i] = persons.get(id);
            i++;
        }
        return p;
    }

} 

1 个答案:

答案 0 :(得分:0)

InetSocketAddress remoteAddress = exchange.getRemoteAddress();
String remoteHost = remoteAddress.getHostName(); 

您确定remoteAddress是否具有值,如果remoteAddress为null,则remoteAddress.getHostName()将抛出NullPointerException.So,您应该添加条件。

InetSocketAddress remoteAddress = exchange.getRemoteAddress();
String remoteHost;
if(remoteAddress != null){
   remoteHost = remoteAddress.getHostName();
}
System.out.println("Who poked us: " +  remoteHost);