Struts2笔记 - Struts2中访问Web元素的3中方法

1、通过RequestAware,SessionAware,ApplicationAware获取:

在Struts2中不能直接访问Request,Session,Application元素,但是可以使用Struts2中提供的RequestAware,SessionAware,ApplicationAware。在这里要分别为三个对象提供setter方法,以便让struts自动执行,使用IoC(控制反转)进行赋值。

下面的LoginAction使用ModelDriven获取User,放入Session中,并在request和application中分别放入“test1”和“test2”。

LoginAction:

public class LoginAction extends ActionSupport implements ModelDriven,RequestAware,SessionAware, ApplicationAware {
private Map<String, Object> request;
private Map<String, Object> session;
private Map<String, Object> application;
private User user = new User();

public void setSession(Map<String, Object> session) {
    this.session = session;
}
public void setRequest(Map<String, Object> request) {
    this.request = request;
}
public void setApplication(Map<String, Object> application) {
    this.application = application;
}
public void setUserService(UserServiceImpl userService) {

    this.userService = userService;
}
public String execute() {
    session.put("user", userRe);
    request.put("req", "test1");
    application.put("app", "test2");
    return "result";
}

}

在页面中读取保存的数据可以用HttpServletRequest,HttpSession,ServletContext等直接访问,也可以使用Struts标签通过Stack Context访问。

在页面中可以按照以下方式读取保存的数据:

<img class=”user_photo” src=”<s:property value=”#session.user.userPhoto” />” />
<!-- userPhoto为User的一个属性 –>

<s:property value=”#request.req”/>

<%=request.getAttribute(“req”) %>

<s:property value=”#application.app”/> <%=application.getAttribute(“app”) %>

<s:property value=”#attr.user.userPhoto”/>

<s:property value=”#attr.req”/>

<s:property value=”#attr.app”/>

2、通过ActionContext获取Map类型的元素:

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;
}

3、通过ServletActionContext获取原始的web元素类型:

private HttpServletRequest request;
private HttpSession session;
private ServletContext application;
public LoginAction3() {
request = ServletActionContext.getRequest();
session = request.getSession();
application = session.getServletContext();
}

arthinking wechat
欢迎关注itzhai公众号