01 April 2017

Struts 2 Framework: 4 Cách tạo Request Session Application trong Struts 2 Java Web

Request: Tồn tại với lần gọi
Session: Tồn tại trong phiên làm việc của máy tính
Appliaction: Tồn tại từ khi khởi tạo đến lúc server ngừng hoạt động
LoginAction1.java
Java Web 2017

public class LoginAction1 extends ActionSupport {

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

}
LoginAction2.java
Java Web 2017

public class LoginAction2 extends ActionSupport implements RequestAware, SessionAware, ApplicationAware {

    private Map<String, Object> request;
    private Map<String, Object> session;
    private Map<String, Object> application;

   //DI dependency injection
   //IoC inverse of control
    public String execute() {
        request.put("r1", "r1");
        session.put("s1", "s1");
        application.put("a1", "a1");
        return SUCCESS;
    }

    @Override
    public void setRequest(Map<String, Object> request) {
        this.request = request;
    }

    @Override
    public void setSession(Map<String, Object> session) {
        this.session = session;
    }

    @Override
    public void setApplication(Map<String, Object> application) {
        this.application = application;
    }

}
LoginAction3.java
Java Web 2017

public class LoginAction3 extends ActionSupport {

    private HttpServletRequest request;
    private HttpSession session;
    private ServletContext application;

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

    public String execute() {
        request.setAttribute("r1", "r1");
        session.setAttribute("s1", "s1");
        application.setAttribute("a1", "a1");
        return SUCCESS;
    }

}
LoginAction4.java
Java Web 2017
public class LoginAction4 extends ActionSupport implements ServletRequestAware {

    private HttpServletRequest request;
    private HttpSession session;
    private ServletContext application;

    public String execute() {
        request.setAttribute("r1", "r1");
        session.setAttribute("s1", "s1");
        application.setAttribute("a1", "a1");
        return SUCCESS;
    }

    @Override
    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
        this.session = request.getSession();
        this.application = session.getServletContext();
    }
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang