import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
protected HttpServletRequest getRequest() {
return ServletActionContext.getRequest();}
protected HttpSession getSession() {
return ServletActionContext.getRequest().getSession();
}
protected HttpServletResponse getResponse() {
return ServletActionContext.getResponse();
}
/**
* 放一个对象到session里
*
* @param sessionKey
* @param obj
*/
public void setObjToSession(String sessionKey, Object obj) {
ActionContext context = ActionContext.getContext();
Map<String, Object> sessionMap = context.getSession();
sessionMap.put(sessionKey, obj);
}
public Object getObjFromSession(String sessionKey) {
ActionContext context = ActionContext.getContext();
Map<String, Object> sessionMap = context.getSession();
Object obj = sessionMap.get(sessionKey);
return obj;
}
public void removeFromSession(String key) {
ActionContext context = ActionContext.getContext();
Map<String, Object> sessionMap = context.getSession();
sessionMap.remove(key);
}
/**
* 往cookie里塞值
*
* @param key
* @param value
* @param time
*/
public void addCookie(String key, String value, int time) {
Cookie cookie = new Cookie(key, value);
cookie.setMaxAge(time);
cookie.setPath("/");
ServletActionContext.getResponse().addCookie(cookie);
}
/**
* 根据key 删除cookie
*
* @param key
*/
public void removeCookie(String key) {
Cookie cookie = new Cookie(key, null);
cookie.setMaxAge(0);
cookie.setPath("/"); // 项目所有目录均有效,这句很关键,否则不敢保证删除
ServletActionContext.getResponse().addCookie(cookie);
}
/**
* 根据key 从cookie中获取值
*
* @param key
* @return
*/
public String getValueFromCookie(String key) {
Cookie cookies[] = ServletActionContext.getRequest().getCookies();
if (cookies != null && cookies.length > 0) {
for (Cookie cookie : cookies) {
if (cookie != null && StringUtils.equals(key, cookie.getName()))
return cookie.getValue();
}
}
return null;
}