1

Greetings,

I have a servlet which pulls an "action" parameter from a querystring. Based on this string I perform the required action.

What is the best way to check the value of the "action" parameter. Currently my code is a long if, else if, else if, else if...when I'd rather have some kind of mapping from string to method where I didn't have so many branch conditions.

Regards,

Ken

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
kobrien
  • 2,931
  • 2
  • 24
  • 33

3 Answers3

3

Populate a Map<String, Action> where String represents the condition for which you would like to grab the action and Action is the interface which you've definied for your actions.

E.g.

Action action = actions.get(request.getMethod() + request.getPathInfo());
if (action != null) {
    action.execute(request, response);
}

You can find a detailed example in this answer.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

One possible way is to keep them in a file (XML file or Properties file). Load them into the memory. It can be stored in some Map. Based the key, the operation(value) can be decided.

aNish
  • 1,079
  • 6
  • 11
0

Maybe using a helper class with an enum type might help:

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;
    }
}

Then, your servlet will have something short and simple like:

ServletAction sa = ActionHelper.getAction(request.getParameter("action"));
switch (sa) {
    case ServletAction.ActionEdit:
        //
        break;
    // ... more cases
}
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292