SSH总结(一)
其实学习struts等框架,不仅要知道怎么用,我们还应该多去看看框架的源码,知道为什么可以这样使用,凡事都知道为什么,以这样的态度学习,我们才能更加深一步的理解原理好实现方式,本类博客主要是个人学习总结。如有不足之处,请多多指教,以便我能更快的进步。!!!!
1、获取reqesut和response对象方法
1 2 3 | Map request = (Map)ActionContext.getContext().get( "request" ); HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse() |
1 2 3 4 5 6 7 8 9 10 | public class BaseAction<T> extends ActionSupport implements ModelDriven<T>,ServletRequestAware{ protected HttpServletRequest request @Override public void setServletRequest(HttpServletRequest arg0) { this .request=arg0; } } |
2、前后台传值
这里主要是实现ModelDriven接口,代码如下:
1 2 3 4 5 6 7 8 | 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拦截器把参数放入值栈中。这样就可以实现参数的注入了。再想想前台和后台的传值方法,也就不难理解他的原理啦!!!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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(),代码使用如下:
1 2 3 4 5 6 | ActionInvocation actionInvocation = ActionContext.getContext().getActionInvocation(); actionInvocation.addPreResultListener( new PreResultListener(){ public void beforeResult(ActionInvocation action,String resultCode){ //TO-DO } }); |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步