在没有使用Struts2之前,都习惯使用HttpServletRequest和HttpSession对象来操作相关参数,下面介绍一下在Struts2中访问隐藏的HttpServletRequest和HttpSession的两种方法:
1.非Ioc方式
这种方式主要是利用了com.opensymphony.xwork2.ActionContext类以及ora.apache.struts2.ServletActionContext类,具体的方法如下所示。
获得request对象:
1).HttpServletRequest request = ServletActionContext.getRequest ();
2).ActionContext ct= ActionContext.getContext();
HttpServletRequest request=
(HttpServletRequest)ct.get(ServletActionContext.HTTP_REQUEST);
获得session对象:
在Struts2中底层的session都被封装成了Map类型,我们称之为SessionMap,而平常我们所说的session则是指HttpSession对象,具体的获得方法如下所示。
1).Map session=ActionContext.getSession();
2).Map session=(Map)ActionContext.getContext().get(ActionContext.SESSION);
得到这个SessionMap之后我们就可以对session进行读写了,如果我们想得到原始的HttpSession可以首先得到HttpServletRequest对象,然后通过request.getSession()来取得原始的HttpSession对象。一般情况下SessionMap已经可以完成所有的工作,我们不必再去强行使用底层的session了。
2.IoC方式
这种方式相对来说变化就比较少了,下面给出代码大家自己看吧:
- 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;
- publicclass 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;
- }
- }