簡體   English   中英

Servlet請求處理

[英]Servlet request processing

問候,

我有一個servlet,它從查詢字符串中提取“操作”參數。 基於此字符串,我執行所需的操作。

檢查“ action”參數值的最佳方法是什么。 當前我的代碼很長,如果,如果,如果,如果,否則,如果...,當我希望從字符串到方法的某種映射,而我沒有那么多分支條件的時候。

問候,

填充一個Map<String, Action> ,其中String表示您要抓住該動作的條件,而Action是您為動作定義的接口。

例如

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

您可以在此答案中找到詳細的示例。

一種可能的方法是將它們保存在文件(XML文件或屬性文件)中。 將它們加載到內存中。 它可以存儲在某些Map中。 根據密鑰,可以確定操作(值)。

也許使用帶有枚舉類型的幫助器類可能會有所幫助:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM