Struts2中访问HttpServletRequest和HttpSession
http://pengfeng.iteye.com/blog/212358
1.非Ioc方式
这种方式主要是利用了com.opensymphony.xwork2.ActionContext类以及ora.apache.struts2.ServletActionContext类,具体的方法如下所示。
获得request对象:
1).
HttpServletRequest request = ServletActionContext.getRequest ();
ActionContext ct= ActionContext.getContext(); HttpServletRequest request=(HttpServletRequest)ct.get(ServletActionContext.HTTP_REQUEST);
Map session=ActionContext.getSession();
Map session=(Map)ActionContext.getContext().get(ActionContext.SESSION);
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.ServletResponseAware; import org.apache.struts2.interceptor.SessionAware; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class IoCServlet extends ActionSupport implements SessionAware, ServletRequestAware, ServletResponseAware { private String message; private Map att; private HttpServletRequest request; private HttpServletResponse response; public String getMessage() { return message; } publicvoid setSession(Map att) { this.att = att; } publicvoid setServletRequest(HttpServletRequest request) { this.request = request; } publicvoid setServletResponse(HttpServletResponse response) { this.response = response; } @Override public String execute() { att.put("msg", "Hello World from Session!"); HttpSession session = request.getSession(); StringBuffer sb =new StringBuffer("Message from request: "); sb.append(request.getParameter("msg")); sb.append("<br>Response Buffer Size: "); sb.append(response.getBufferSize()); sb.append("<br>Session ID: "); sb.append(session.getId()); message = sb.toString(); return SUCCESS; } }