Java 网络服务似乎没有存储变量?

Java web service seemingly not storing variable?

编辑:问题有两个方面,第一个字典应该是静态的,而且我在本应使用 .containsKey() 的地方使用 .contains()

我正在尝试做一个简单的 java 客户端和服务器设置,这就是我所拥有的并且我似乎无法发现我完成它的方式有什么问题但是每当我运行 我得到输出的代码:

Result = Added

Result = This word is not in the dictionary, please use the add function.

这告诉我当我添加一个词时服务器没有存储对地图所做的更改,我在这里缺少一些非常简单的东西吗?

如果需要,我可以添加更多信息。

这是我的客户端代码:

public class Client {
 @WebServiceRef(wsdlLocation = 
        "http://localhost:8080/P1Server/ServerService?wsdl")

public static void main(String[] args) { 
try { 
    package1.ServerService service = new package1.ServerService(); 
    package1.Server port = service.getServerPort(); 

    String result = port.addWord("Test", "This is a test."); 
    System.out.println("Result = " + result); 

    result = port.getDefiniton("Test");
    System.out.println("Result = " + result); 
}catch(Exception ex)
{ 
    System.out.println("Gone Wrong"); 
}

这是我的相关服务器代码:

@WebService
public class Server {

private **static**ConcurrentHashMap<String,String> dictionary;    

public Server() {
    this.dictionary = new ConcurrentHashMap<>();
}

@WebMethod
public String addWord(String word, String definition){
    if(dictionary.contains(word.toLowerCase())){
        return "This word is already in the dictionary, "
                + "please use the update function.";
    }else{
        dictionary.put(word.toLowerCase(), definition);
        return "Added";
    }
}
@WebMethod
public String getDefiniton(String word){
    if(dictionary.contains(word.toLowerCase())){
        return dictionary.get(word);

    }else{
        return "This word is not in the dictionary, "
                + "please use the add function.";
    }
}

Web 服务本质上是无状态的。每个 Web 请求都将获得自己的上下文和实例。因此,为 port.addWord() 请求提供服务的服务器实例可能不同于为 port.getDefinition() 提供服务的服务器实例。在这种情况下,将结果放入其中的字典映射与用于检索结果的字典映射不同。

为了使其工作,数据需要以某种方式保存在服务器端。这可以通过数据库来完成。或者,如果您只是出于测试目的这样做,请将字典的定义更改为静态,以便 Server 的所有实例共享同一个映射。

定义字典为静态变量。这样在服务器端创建的 Web 服务实例的每个实例都将使用相同的字典来 put/get 数据。

private static ConcurrentHashMap<String,String> dictionary;

您的问题与网络服务无关。 问题出在你的逻辑上

修改您的方法如下:

public String addWord(String word, String definition) {
        if (dictionary.containsKey(word.toLowerCase())) {
            return "This word is already in the dictionary, "
                    + "please use the update function.";
        } else {
            dictionary.put(word.toLowerCase(), definition);
            return "Added";
        }
    }

    public String getDefiniton(String word) {
        if (dictionary.containsKey(word.toLowerCase())) {
            return dictionary.get(word.toLowerCase());

        } else {
            return "This word is not in the dictionary, "
                    + "please use the add function.";
        }
    }

它会起作用的。 希望这有帮助。