通常我们在写Action代码的时候,通常需要用到request,response,session,等 这时候extends一个公共action就方便多了!
public class BaseAction extends ActionSupport implements ServletRequestAware, ServletResponseAware {
private static final long serialVersionUID = 1L;
protected HttpServletRequest servletRequest;
protected HttpServletResponse servletResponse;
/**
* 获取Session,Map 跟 HttpSession 的同一引用
*/
protected Map<String, Object> getSession() {
// 判断Session有没过期
if (!ServletActionContext.getRequest().isRequestedSessionIdValid()) {
try {
ServletActionContext.getResponse().sendRedirect("/login.jsp");
} catch (IOException e) {
}
}
return ActionContext.getContext().getSession();
}
/**
* 设值到ActionContext 的ContextMap中
*/
protected void putInContext(String key, Object value) {
getActionContext().put(key, value);
}
/**
* 保存的Session域中的
*/
protected void putInSession(String key, Object value) {
getSession().put(key, value);
}
/**
* 获取Session 里的对象
*/
@SuppressWarnings("unchecked")
protected <T> T getInSession(String key) {
return (T) getSession().get(key);
}
/**
* 得到struts2 的 ActionContext 对象
*/
protected ActionContext getActionContext() {
return ActionContext.getContext();
}
/**
* 获取Session里的对象
*/
protected <T> T getInSession(String key) {
return (T) getSession().get(key);
}
/**
* 重新对request域进行封装
* @return
*/
public Map<String, String> getParameter() {
Map hmParam = new HashMap();
for (Iterator iter = getServletRequest().getParameterMap().keySet().iterator(); iter.hasNext();) {
String name = (String) iter.next();
hmParam.put(name, getServletRequest().getParameter(name));
}
return hmParam;
}
public void setServletRequest(HttpServletRequest servletRequest) {
this.servletRequest = servletRequest;
}
public void setServletResponse(HttpServletResponse servletResponse) {
this.servletResponse = servletResponse;
}
public HttpServletRequest getServletRequest() {
return servletRequest;
}
public HttpServletResponse getServletResponse() {
return servletResponse;
}
public Map<String, Object> getSession() {
return (Map<String, Object>) this.getServletRequest().getSession();
}
public String getSessionId() {
return this.getServletRequest().getSession().getId();
}
}