我正在使用JQuery
从多个位置调用Java Servlet
,以调用servlet中的多个不同方法。目前,我传递一个字符串(称为methodName),然后使用不断增加的IF ELSE块来查看要调用哪个函数:
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")));
}
然而,这对我来说似乎非常笨拙和低效,特别是随着未来方法数量的增加。有没有更有效的方法来比较字符串?或者我应该简单地为每个方法制作一个单独的 servlet(并简单地在processRequest
中进行处理?
我建议,你应该考虑休息的网络服务。REST 定义了一组体系结构原则,通过这些原则,您可以设计侧重于系统资源的 Web 服务,包括用不同语言编写的各种客户端如何通过 HTTP 寻址和传输资源状态。
有许多开源可以帮助您非常轻松地实现 restful servlet......其中之一是Apache Wink http://incubator.apache.org/wink/
在 IBM Developerworks 中有一篇关于相同的好文章
http://www.ibm.com/developerworks/web/library/wa-apachewink1/
http://www.ibm.com/developerworks/web/library/wa-apachewink2/index.html
http://www.ibm.com/developerworks/web/library/wa-apachewink3/index.html
其他选择 :
春季MVC
Apache CXF http://cxf.apache.org/docs/jax-rs.html
我建议将每个方法都设置为实现简单接口的对象。 在您的类中,创建一个 HashMap 将接口的每个实现链接到其各自的键。
接口
public interface MyMethod {
public String call();
}
实现
public class MethodOne implements MyMethod{
}
映射和呼叫
private Map<String, MyMethod> mappings = new HashMap<String,MyMethod>();
static{
mappings.put("method1", new MethodOne());
//.. other mappings
}
public String methodCaller(String methodName) throws SQLException, IOException
{
MyMethod myMethod = mappings.get(methodName);
return myMethod.call();
}
我会简单地开始使用整数。
在你的JavaScript中有一个这样的函数
function convertmethod(methodname)
{
thereturn = -1;
switch(methodname) {
case "Method1" : thereturn = 1;break;
case "Method2" : thereturn = 2;break;
case "Method3" : thereturn = 3;break;
case "Method4" : thereturn = 4;break;
}
return thereturn;
}
然后在您的 java 代码中,您还可以使用开关
public String methodCaller(int methodName) throws SQLException, IOException
{
switch(methodName)
{
case 1: return method1(attr("permit"));break;
case 2: return method2(attr("permit"));break;
case 3: return method3(attr("ring"));break;
case 4: return method4(attr("gridRed"));break;
}
}