struts2的Action类中获得请求对象的四种方法

第一种形式:

public class LoginAction1 extends ActionSupport
{
 private Map request;
 private Map session;
 private Map application;
 
 public LoginAction1()
 {
  request = (Map)ActionContext.getContext().get("request");
  session = ActionContext.getContext().getSession();
  application = ActionContext.getContext().getApplication();
 }
 
 public String execute()
 {
  request.put("r1", "r1");
  session.put("s1", "s1");
  application.put("a1", "a1");
  return SUCCESS;
 }
}

 

第二种形式:

public class LoginAction2 extends ActionSupport implements RequestAware,SessionAware,ApplicationAware
{
 private Map<String,Object> request;
 private Map<String,Object> session;
 private Map<String,Object> application;
 
 public String execute()
 {
  request.put("r1", "r2");
  session.put("s1", "s2");
  application.put("a1", "a2");
  return SUCCESS;
 }

 @Override
 public void setRequest(Map<String, Object> request)
 {
  // TODO Auto-generated method stub
  this.request = request;
 }

 @Override
 public void setSession(Map<String, Object> session) {
  // TODO Auto-generated method stub
  this.session = session;
 }
 
 @Override
 public void setApplication(Map<String, Object> application) {
  // TODO Auto-generated method stub
  this.application = application;
 }
}

 

第三种形式:

public class LoginAction3 extends ActionSupport
{
 private HttpServletRequest request;
 private HttpSession session;
 private ServletContext application;
 
 public LoginAction3()
 {
  request = ServletActionContext.getRequest();
  session = request.getSession();
  application = session.getServletContext();
 }
 
 public String execute()
 {
  request.setAttribute("r1", "r3");
  session.setAttribute("s1", "s3");
  application.setAttribute("a1", "a3");
  return SUCCESS;
 }
}

第四种形式:

public class LoginAction4 extends ActionSupport implements ServletRequestAware
{
 private HttpServletRequest request;
 private HttpSession session;
 private ServletContext application;
 
 public String execute()
 {
  request.setAttribute("r1", "r4");
  session.setAttribute("s1", "s4");
  application.setAttribute("a1", "a4");
  return SUCCESS;
 }

 @Override
 public void setServletRequest(HttpServletRequest request)
 {
  // TODO Auto-generated method stub
  this.request = request;
  this.session = request.getSession();
  this.application = session.getServletContext();
 }
}

其中第二种方式最常用

你可能感兴趣的:(struts2的Action类中获得请求对象的四种方法)