2013-10-23 36 views
2

在此代碼中,我使用ActionContext從Request對象獲取Session和ServletActionContext。我覺得這是不好的做法,因爲只有Action對象只能用於Request對象。如何使用ActionContext中的參數,請求和會話對象?

ActionContext的Request對象是否等價於Servlet中的Request對象?如果是,如何使用它獲取請求參數?

Map session = (Map) ActionContext.getContext().getSession(); 
HttpServletRequest request = ServletActionContext.getRequest(); 
String operatorId = request.getParameter("operatorId"); 
session.put("OperatorId", operatorId); 
// getting hashmap from Bean 
analysisNames= slsLoginDetailsRemote.getAnalysisNamesIdMap(); 
// sending map for multiselect 
session.put("AnalysisNames",analysisNames); 
+0

use request.getParameter(「parameter_name」); –

回答

7

在Struts2,會話映射和請求地圖是底層HttpServletRequest和Session對象的包裝器。

如果您只需要訪問屬性,請使用包裝。

如果您在InterceptorPOJO之內,請使用ActionContext獲取它們(包裝器和底層HTTP對象)僅限

如果你是一個Action內,最好的做法是實現一個接口,它會自動填充您的操作的對象:


爲了得到請求地圖包裝use RequestAware

public class MyAction implements RequestAware { 
    private Map<String,Object> request; 

    public void setRequest(Map<String,Object> request){ 
     this.request = request; 
    } 
} 

獲取會話映射包裝use SessionAware

public class MyAction implements SessionAware { 
    private Map<String,Object> session; 

    public void setSession(Map<String,Object> session){ 
     this.session = session; 
    } 
} 

要得到根本HttpServletRequest的HttpSession中對象,use ServletRequestAware

public class MyAction implements ServletRequestAware { 
    private javax.servlet.http.HttpServletRequest request; 

    public void setServletRequest(javax.servlet.http.HttpServletRequest request){ 
     this.request = request; 
    } 

    public HttpSession getSession(){ 
     return request.getSession(); 
    } 
} 

也就是說,JSP頁面和操作之間的標準數據流,或行動和行動,通過訪問者/變異者獲得,更好地被稱爲Getters和Sette RS。不要重新發明輪子。

1

首先

ActionContext's Request object is equivalent to the Request object in Servlets 

如果您使用的框架Struts等。這是一個不好的做法。您無需從ServletActionContext創建HttpServletRequest對象來獲取請求參數。只需在action類中聲明請求參數,併爲它們寫入getter和setter將會獲得您的值。

UPDATE

如果你想在動作類的請求參數,你可以做這樣的:

public class MyAction extends ActionSupport implements SessionAware{ 
    private String operatorId; 
    private Map<String, Object> session; 


    //Getter and setters 
    public String getOperatorId() { 
      return operatorId; 
     } 

     public void setOperatorId(String operatorId) { 
      this.operatorId = operatorId; 
     } 

@Override 
    public void setSession(Map<String, Object> session) { 
     this.session = session; 

    } 
    } 

所以,現在,如果我想使用operatorId任何地方所有我需要做的是getOperatorId()或直接使用operatorId。 :)

如果發現Action類實現SessionAware更合理,因爲我可以直接訪問會話對象,如@Andrea提到..所以現在我可以直接使用session.put("OperatorId", operatorId);session.put("AnalysisNames",analysisNames);

+0

如果我實現如上面的答案中所示的RequestAware接口,我可以通過doung request.get(「paramName」)獲取請求參數??? –

+1

是的,你可以..但是如果你正在編寫你的邏輯到Action類中,你可以避免這個實現。您可以避免Action類的RequestAware接口...請參閱我的更新例如.. – DarkHorse

相關問題