2010-11-29 113 views
1

問候,小服務程序請求處理

我有一個servlet從查詢字符串中提取「action」參數。基於這個字符串,我執行所需的操作。

檢查「動作」參數值的最佳方法是什麼?目前我的代碼是一個很長的if,else if,else if,else if ...當我寧願有一些從字符串到方法的映射時,我沒有那麼多分支條件。

問候,

回答

3

填充Map<String, Action>其中String代表您想要採取該操作的條件,Action是您爲自己的操作定義的接口。

E.g.

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

你可以在this answer找到一個詳細的例子。

0

一種可能的方式是讓他們在一個文件(XML文件或屬性文件)。 將它們加載到內存中。它可以存儲在某個地圖中。 基於該鍵,可以決定操作(值)。

0

也許使用一個輔助類與枚舉類型可能會有所幫助:

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 
}