Struts2中访问Web元素的3中方法

Struts2笔记 – Struts2中访问Web元素的3中方法 本文由 arthinking 发表于445 天前 ⁄ J2EE ⁄ 暂无评论 ⁄ 被围观 1,615 views+
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 request;
    private Map session;
    private Map application;
    private User user = new User();

    public void setSession(Map session) {
        this.session = session;
    }
    public void setRequest(Map request) {
        this.request = request;
    }
    public void setApplication(Map 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访问。

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

class="user_photo" src="userPhoto" />" />



"#request.req"/>

<%=request.getAttribute("req") %> 
"#application.app"/> <%=application.getAttribute("app") %>
"#attr.user.userPhoto"/>
"#attr.req"/>
"#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();
    }

你可能感兴趣的:(Struts2中访问Web元素的3中方法)