strut2得到Respone对象---实现ServletResponseAware接口

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.Action;

public class LoginAction implements Action, ServletResponseAware {

//需要访问的HttpServletResponse对象
private HttpServletResponse respone;

//封装请求参数的两个属性
private String username;
private String password;

public HttpServletResponse getRespone() {
   return respone;
}

public void setRespone(HttpServletResponse respone) {
   this.respone = respone;
}

public String getUsername() {
   return username;
}

public void setUsername(String username) {
   this.username = username;
}

public String getPassword() {
   return password;
}

public void setPassword(String password) {
   this.password = password;
}

/**
* 实现ServletResponseAware接口必须实现的方法
*/
public void setServletResponse(HttpServletResponse respone) {
   this.respone = respone;
}

/**
* 处理用户请求的execute方法
*/
public String execute() throws Exception {
   //创建一个user对象
   Cookie cookie = new Cookie("user",getUsername());
   //设置Cookie的最大生存时间
   cookie.setMaxAge(60*60);
   //使用HttpServletResponse对象添加Cookie对象
   respone.addCookie(cookie);

   //企图在Servlet中直接生成输出的代码,
   //要标准的servlet中会生成对客户端的输出,但要Struts2的Action中,没有任何实际意义
   //respone.getWriter().println("Hello World");


   return SUCCESS;
}
}

//从系统中读取Cookie的值:${cookie.user.value}

你可能感兴趣的:(apache,servlet)