1.获得Map类型的request,session,application
(方法一)(依赖Struts2容器)
public class LoginAction extends ActionSupport implements ModelDriven<User> {
private User user = new User();
private Map request;
private Map session;
private Map application;
public LoginAction(){
request = (Map) ActionContext.getContext().get("request");//获得Map类型的request
session = ActionContext.getContext().getSession(); //获得Map类型的session
application = ActionContext.getContext().getApplication();//获得Map类型的application
}
@Override
public String execute() throws Exception {
request.put("uname", user.getUsername());
session.put("uname", user.getUsername());
application.put("uname", user.getUsername());
return SUCCESS;
}
public User getModel() {
return user;
}
}
取值:
<s:property value="#request.uname"/><br>
<s:property value="#session.uname"/><br>
<s:property value="#application.uname"/>
(方法二:)(IoC)
public class LoginAction extends ActionSupport implements ModelDriven<User>,RequestAware,SessionAware,ApplicationAware{
private User user = new User();
private Map request;
private Map session;
private Map application;
@Override
public String execute() throws Exception {
request.put("uname", user.getUsername());
session.put("uname", user.getUsername());
application.put("uname", user.getUsername());
return SUCCESS;
}
public User getModel() {
return user;
}
public void setApplication(Map<String, Object> application) {
this.application =application;
}
public void setSession(Map<String, Object> session) {
this.session = session;
}
public void setRequest(Map<String, Object> request) {
this.request = request;
}
}
2.获取HttpServletRequest,HttpSession,ServletContext对象
方法一:IoC
public class UserLoginAction extends ActionSupport implements ServletRequestAware {
private String username;
private String password;
private HttpServletRequest request;
private HttpSession session;
private ServletContext application;
public void setServletRequest(HttpServletRequest request) {
this.request=request; //获取request对象
this.session=request.getSession(); //获取session对象
this.application= session.getServletContext();//获取application对象
}
@Override
public String execute() throws Exception {
application.setAttribute("uname", username);
return SUCCESS;
}
方法二:依赖Struts2容器
public class LoginAction extends ActionSupport implements ModelDriven<User>{
private User user = new User();
private HttpServletRequest request;
private HttpSession session;
private ServletContext application;
public LoginAction(){
request = ServletActionContext.getRequest();
session = request.getSession();
application = session.getServletContext();
}
@Override
public String execute() throws Exception {
request.setAttribute("uname", user.getUsername());
session.setAttribute("uname", user.getUsername());
application.setAttribute("uname", user.getUsername());
return SUCCESS;
}
public User getModel() {
return user;
}