struts中操作request,session
在Action类中操作request,session
方法一、利用ActionContext.getContext().get("request");
//返回的是Map集合 Map<String,Object> request = (Map<String,Object>)ActionContext.getContext().get("request"); //放入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 HttpServletRequest request = ServletActionContext.getRequest(); //setsetAttribute放入 request.setAttribute(arg0, arg1); //etAttribute取出 request.getAttribute(arg0) //生成Session需要先生成Request HttpServletRequest req = ServletActionContext.getRequest(); //再用request.getSession();生成session 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()方法实现
//放入 request.put(key, value); //取出 request.get("key"); session.put(key, value); session.get(key);