Struts 2 读书笔记-----使用PreResultListener

来源:互联网 发布:淘宝叮当数码在哪里 编辑:程序博客网 时间:2024/05/16 02:02
           PreResultListener是要给监听器接口,他可以在Action完成控制处理之后,系统转入实际的物理视图之间被回调。

           Struts 2 可以由ActionInvocation的addPreResultListener()方法来完成。

           Struts 2 可以由Action和拦截器添加PreResultListener监听器。当为Action添加了改监听器,该监听器就可以再应用转入到实际物理视图之前回调该监听器的beforeResult()方法;当为拦截器添加监听器后,该监听器会对该拦截器所拦截的所有action都起作用。

          如:

       

public class LoginRegistAction extends ActionSupport{private String username;           //用户名private String password;           //密码private String tip;                //封装结果public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getTip() {return tip;}public void setTip(String tip) {this.tip = tip;}//Action包含的注册控制逻辑public String regist(){ActionContext.getContext().getSession().put("user", getUsername());return SUCCESS;}//Action包含的登陆控制逻辑public String login(){ActionInvocation actionInvocation = ActionContext.getContext().getActionInvocation();actionInvocation.addPreResultListener(new PreResultListener(){public void beforeResult(ActionInvocation action,String resultCode){System.out.println("返回的逻辑视图名字为:"+resultCode);//在返回resultCode之前加入一个额外的数据action.getInvocationContext().put("extra", new java.util.Date()+"由"+resultCode+"逻辑视图转入");}});if(getUsername().equals("chenssy")&&getPassword().equals("chentmt")){ActionContext.getContext().getSession().put("user", getUsername());setTip("欢迎,"+getUsername()+",您已经成功登陆!");return SUCCESS;}else {return ERROR;}}}


          上面的红色字体代码就示范了为Action添加PreResultListener,这样改监听器就可以在转入物理视图之前激发该监听器

           输入正确的用户名和密码登陆后,就可以得到如下页面:

      

通过上面我们可以看到,通过使用PreResultListener监听指定Action转入不同Result的细节。

 

读李刚《轻量级java EE企业应用实战(第三版)—struts 2+Spring 3+Hibernate整合开发》

 

原创粉丝点击