Here in this code I am using ActionContext to get Session and ServletActionContext from Request object. I feel this is bad practice, as one must use ActionContext only for Request object.
Is ActionContext's Request object equivalent to the Request object in Servlets ? If yes, how to get request parameters using it ?
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);
In Struts2, Session Map and Request Map are wrappers for the underlying HttpServletRequest and Session objects.
If you only need to access attributes, use the wrappers.
Use ActionContext to get them (both the wrappers and the underlying HTTP objects) only if you are inside an Interceptor
or a POJO
.
If you are inside an Action
, the best practice is to implement an Interface that will automatically populate your Action's object:
To get the Request Map wrapper, use RequestAware
public class MyAction implements RequestAware {
private Map<String,Object> request;
public void setRequest(Map<String,Object> request){
this.request = request;
}
}
To get the Session Map wrapper, use SessionAware
public class MyAction implements SessionAware {
private Map<String,Object> session;
public void setSession(Map<String,Object> session){
this.session = session;
}
}
To get the underlying HttpServletRequest and HttpSession objects, 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();
}
}
That said, the standard data flow between JSP pages and Actions, or Actions and Actions, is obtained through Accessors / Mutators, better known as Getters and Setters. Don't reinvent the wheel.