struts如何在Action类中操作request,session
在servlet中,通过request.getparameter与setparameter来实现后端与前端jsp页面的数据交互,那么在struts中,也有几种方式来操作request,session实现后端与前端的交互。
方法一、利用ActionContext.getContext().get("request");
Map<String,Object> request = (Map<String,Object>)ActionContext.getContext().get("request"); request.put(key, value); request.get("key"); Map<String,Object> session = ActionContext.getContext().getSession(); session.put(key, value); session.get(key);
方法二、使用ServletActionContext.getRequest();
HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute(arg0, arg1); request.getAttribute(arg0) HttpServletRequest req = ServletActionContext.getRequest(); HttpSession session = req.getSession(); session.setAttribute(arg0, arg1); session.getAttribute(arg0);
方法三、使用RequestAware,SessionAware接口
1.实现这两个接口
public class NewsAction extends ActionSupport implements RequestAware,SessionAware {}
2.定义两个成员变量
private Map<String,Object> session; private Map<String,Object> request;
3.重写接口中的方法
@Override public void setRequest(Map<String, Object> arg0) { this.request = arg0; } @Override public void setSession(Map<String, Object> arg0) { // TODO Auto-generated method stub this.session = arg0; }
4.使用session.put(),session.get(),request.put(),request.get()方法实现
public class NewsAction extends ActionSupport implements RequestAware,SessionAware { private Map<String,Object> session; private Map<String,Object> request; @Override public void setRequest(Map<String, Object> arg0) { this.request = arg0; } @Override public void setSession(Map<String, Object> arg0) { // TODO Auto-generated method stub this.session = arg0; } }