SSH總結(一)


      其實學習struts等框架,不僅要知道怎么用,我們還應該多去看看框架的源碼,知道為什么可以這樣使用,凡事都知道為什么,以這樣的態度學習,我們才能更加深一步的理解原理好實現方式,本類博客主要是個人學習總結。如有不足之處,請多多指教,以便我能更快的進步。!!!!

1、獲取reqesut和response對象方法

Map request = (Map)ActionContext.getContext().get("request");
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse()

  

實現ServletRequestAware接口通過IOC機制注入Request對象
public class BaseAction<T> extends ActionSupport implements ModelDriven<T>,ServletRequestAware{

protected HttpServletRequest request

@Override
 public void setServletRequest(HttpServletRequest arg0) {
    this.request=arg0;
 }

}

 

2、前后台傳值

這里主要是實現ModelDriven接口,代碼如下:

public class BaseAction<T> extends ActionSupport implements ModelDriven<T> {
protected T model;
@Override
	public T getModel() {
		return model;
	}

}

 如果頁面中input標簽的name和javabean中的屬性一一對應,那么只需要這樣,后台就可以把值注入到實體對象中。知道了是怎么使用的,但是我們還應該知道它的原理是什么!!!

實現ModelDriven就可以注入參數,主要是struts框架中有ModelDrivenInterceptor,打開源代碼,可以在源代碼中看到ModelDriven的攔截器和實現代碼,繼續閱讀struts的源代碼,在下面的一段源代碼中,struts攔截器把參數放入值棧中。這樣就可以實現參數的注入了。再想想前台和后台的傳值方法,也就不難理解他的原理啦!!!

public class ModelDrivenInterceptor extends AbstractInterceptor {

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        Object action = invocation.getAction();

        if (action instanceof ModelDriven) {
            ModelDriven modelDriven = (ModelDriven) action;
            ValueStack stack = invocation.getStack();
            Object model = modelDriven.getModel();
            if (model !=  null) {
            	stack.push(model);
            }
            if (refreshModelBeforeResult) {
                invocation.addPreResultListener(new RefreshModelBeforeResult(modelDriven, model));
            }
        }
        return invocation.invoke();
    }
}

 3、PreResultListener 接口

在struts框架中,攔截器分為before、after和PreResultListener 攔截器。after攔截器是指在攔截器中定義的代碼,它們存在於invocation.invoke()代碼執行之前,順序執行;after攔截,是指在攔截器中定義的代碼,它們存在於invocation.invoke()代碼執行之后;有的時候,before攔截和after攔截對我們來說還是滿足不了我們的需求,因為我們需要在Action執行完之后,還沒有回到視圖時執行一些操作。這就可以在Action的方法中進行注冊,使用ActionInvocation.addPreResulteListener(),代碼使用如下:

     ActionInvocation actionInvocation = ActionContext.getContext().getActionInvocation();  
      actionInvocation.addPreResultListener(new PreResultListener(){    
            public void beforeResult(ActionInvocation action,String resultCode){    
                //TO-DO
                }    
        });    

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM