EDIT: The problem was two-fold, first dictionary should be static and also i was using .contains() where i should have used .containsKey()
I'm trying to do a simple java client and server set up, this is what i have got and i can't seem to find anything wrong with the way i have done it but whenever i run the code i get the output:
Result = Added
Result = This word is not in the dictionary, please use the add function.
Which tells me that the server isn't storing the change made the the map when i am adding a word, is there something really simple i am missing here?
I can add anymore information needed if asked.
This is my client code:
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");
}
This is my relevant server code:
@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.";
}
}
Your problem has noting to with webservice. Issue is with you logic
Modify your methods as follows :
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.";
}
}
It will work. Hope this helps.