/** * @author zx */ package com.zhouxiang.action; import javax.servlet.ServletRequestAttributeListener; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import org.apache.struts2.interceptor.ServletRequestAware; import com.opensymphony.xwork2.ActionSupport; /** * @author zx * */ public class LoginAction1 extends ActionSupport implements ServletRequestAware{ private String userName; private String password; private HttpServletRequest request; 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; } public HttpServletRequest getRequest() { return request; } public void setRequest(HttpServletRequest request) { this.request = request; } @Override public void setServletRequest(HttpServletRequest arg0) { // TODO Auto-generated method stub this.request=arg0; } public String validateUser()throws Exception { if(getUserName().endsWith("QQ")&&getPassword().equals("123")) { //调用ServletActionContext的getRequest()方法获取request对象 HttpServletRequest request=ServletActionContext.getRequest(); //调用request对象的getSession()方法获取session对象 HttpSession session=request.getSession(); //调用session对象的方法设置数据 session.setAttribute("username",this.userName); return SUCCESS; } else { return INPUT; } } }
/** * @author zx */ package com.zhouxiang.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; /** * @author zx * */ public class LoginAction1 extends ActionSupport { private String userName; private String password; 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; } public String validateUser()throws Exception { if(getUserName().endsWith("QQ")&&getPassword().equals("123")) { //调用ServletActionContext的getRequest()方法获取request对象 HttpServletRequest request=ServletActionContext.getRequest(); //调用request对象的getSession()方法获取session对象 HttpSession session=request.getSession(); //调用session对象的方法设置数据 session.setAttribute("username",this.userName); return SUCCESS; } else { return INPUT; } } }
原文地址:http://blog.csdn.net/leimengyuanlian/article/details/38150221