1. 程式人生 > >Struts2取得內建物件的4種方式

Struts2取得內建物件的4種方式

一,獲取方式

從Servlet容器中獲取的方法

與Servlet容器無關的獲取方法

IoC方式

非Ioc方式

二,獲取方法

2.1 servlet無關:

2.1.1 非IOC模式

Action程式碼
    //private ActionContext context ;//該方法還可以取得值棧(getValueStack()),使用push(obj)往值棧中放資料  
    private Map request;
    private Map session ;  
    private Map application ;
   
    public LoginAction1(){
       request = (Map)ActionContext.getContext().get("request");   //獲取request
       session = ActionContext.getContext().getSession();          //取得session
       application = ActionContext.getContext().getApplication();   //取得application
      
       request.put("r1","r1");
       session.put("i1","i1");
       application.put("a1","a1");
       return SUCCESS;
    }
JSP程式碼
   <s:property value="#request.r1" />|<%=request.getAttribute("r1") %><br>
   <s:property value="#session.i1" />|<%=session.getAttribute("i1") %><br>
   <s:property value="#application.a1" />|<%=application.getAttribute("a1") %><br>
<s:debug></s:debug>
//後臺使用的是Map型別的request/session/application,前臺可以使用httpServletRequest型別的request物件及其他物件接收到,說明struts2肯定幫我們在Map 和Http之間建立了某種關聯


2.1.2 IOC模式(理論上最常用)

Action程式碼
//DI dependency injection(依賴注入)
//IOC(注射方式) inverse of control(控制反轉)
public classLoginAction2 extends ActionSupport implements RequestAware,SessionAware, ApplicationAware {
    private Map<String,Object> request;//依賴注入,控制反轉
    private Map<String,Object> session;
    private Map<String,Object> application;
 
    public voidsetApplication(Map<String, Object> arg0) {
       this.application = arg0;
    }
    public voidsetSession(Map<String, Object> arg0) {
       this.session = arg0;
    }
    public voidsetRequest(Map<String, Object> arg0) {
       this.request = arg0;
    }
    request.put("r1","r1");
    session.put("i1","i1");
    application.put("a1","a1");
    return SUCCESS;
JSP程式碼(同上)


2.2 servlet有關:

2.2.1 非IOC模式(個人認為最常用)

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


2.2.2  IOC模式

public classLoginAction4 extends ActionSupport implements ServletRequestAware,
       SessionAware,ServletContextAware {
 
    private HttpServletRequest request;
    private Map session; // 此處是Map型別的
    private ServletContext application;
 
    @Override
    public String execute() throws Exception {
       request.setAttribute("r1", "r1");
       session.put("i1","i1");
       application.setAttribute("a1", "a1");
       return super.execute();
    }
    public voidsetServletContext(ServletContext arg0) {
       this.application = arg0;
    }
    public voidsetSession(Map<String, Object> arg0) {
       this.session = arg0;
    }
    public void setServletRequest(HttpServletRequestarg0) {
       this.request = arg0;
    }
}