I’m using JQuery to call a Java Servlet from multiple places to call multiple different methods within the servlet. At the moment, I pass a string (called methodName) and then using an ever increasing IF ELSE block to see which function to call:
public String methodCaller(String methodName) throws SQLException, IOException
{
if(methodName.equals("method1"))
{
return method1(attr("permit"));
}
else if(methodName.equals("method2"))
{
return method2(attr("ring"));
}
else if(methodName.equals("method3"))
{
return method3(attr("gridRef"));
}
else if(methodName.equals("method4"))
{
return method4(attr("ring"));
}
else if(methodName.equals("method6"))
{
return method6(attr("ring"), Integer.parseInt(attr("quantity")));
}
However, this seems awfully clunky and inefficient to me, especially as the amount of methods will increase in future. Is there a more efficient way to compare the strings? Or should I simply make a separate servlet for each method (and simply do the processing in the processRequest?
I would recommend making each one of your methods an object that implements a simple interface. In your class, create a HashMap linking each implementation of the interface to its respective key.
Interface
Implementation
Mapping & Call