【发布时间】:2010-11-29 16:37:13
【问题描述】:
您好,
我有一个从查询字符串中提取“动作”参数的 servlet。基于此字符串,我执行所需的操作。
检查“action”参数值的最佳方法是什么。目前我的代码很长 if, else if, else if, else if...当我宁愿有某种从字符串到方法的映射时,我没有那么多分支条件。
问候,
肯
【问题讨论】:
您好,
我有一个从查询字符串中提取“动作”参数的 servlet。基于此字符串,我执行所需的操作。
检查“action”参数值的最佳方法是什么。目前我的代码很长 if, else if, else if, else if...当我宁愿有某种从字符串到方法的映射时,我没有那么多分支条件。
问候,
肯
【问题讨论】:
填充Map<String, Action>,其中String 表示您想要获取操作的条件,Action 是您为操作定义的接口。
例如
Action action = actions.get(request.getMethod() + request.getPathInfo());
if (action != null) {
action.execute(request, response);
}
你可以在this answer找到一个详细的例子。
【讨论】:
一种可能的方法是将它们保存在一个文件中(XML 文件或属性文件)。 将它们加载到内存中。它可以存储在一些地图中。 根据key,可以决定操作(值)。
【讨论】:
也许使用带有枚举类型的辅助类可能会有所帮助:
public class ActionHelper {
public enum ServletAction {
ActionEdit,
ActionOpen,
ActionDelete,
ActionUndefined
}
public static ServletAction getAction(String action)
{
action = action != null ? action : "";
if (action.equalsIgnoreCase("edit"))
return ServletAction.ActionEdit;
else if (action.equalsIgnoreCase("open"))
return ServletAction.ActionOpen;
else if (action.equalsIgnoreCase("delete"))
return ServletAction.ActionDelete;
return ServletAction.ActionUndefined;
}
}
然后,您的 servlet 将有一些简短的内容,例如:
ServletAction sa = ActionHelper.getAction(request.getParameter("action"));
switch (sa) {
case ServletAction.ActionEdit:
//
break;
// ... more cases
}
【讨论】: