[英]Java web service seemingly not storing variable?
編輯:問題是雙重的,第一個字典應該是靜態的,而且我正在使用.contains(),我應該使用.containsKey()
我正在嘗試做一個簡單的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()請求提供服務的Server實例可以與為port.getDefinition()提供服務的Server實例不同。 在這種情況下,已將結果放入其中的字典映射與用於檢索結果的字典映射不同。
為了使其正常工作,需要以某種方式將數據保留在服務器端。 這可以通過數據庫來完成。 或者,如果只是出於測試目的而進行操作,請將字典的定義更改為靜態,以使Server的所有實例共享同一映射。
將字典定義為靜態變量。 這樣,在服務器端創建的每個Web服務實例實例都將使用相同的詞典來放置/獲取數據。
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.";
}
}
會的。 希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.