struts1的拦截器(1.1)

SAIF(Struts Action Invocation Framework)是一个开源组件,它让Struts框架具备ActionIOC的功能 1.saif.jar包放入你的lib中。 2.创建Interceptor类。 3.interceptor配置文件:interceptor-config.xml。这个配置文件中指定了interceptor类和要被拦截的action。 4.struts-config.xml中指定加载interceptor-config.xml

我们都知道Struts默认没有实现AOP,这和WebWork2想比确实矮了一截,还好,有人(Lars Hoss 和 Don Brown)意识到这点,编写SAIFStruts Action Invocation Framework)弥补了这个缺陷,下面就是SAIF的使用介绍。

SAIF的安装很简单:首先将saif-0.1.jar文档复制到WEB-INF/lib目录下即可,然后修改struts-config.xml文档,将SAIFplugin方式添加到struts-config.xml文档中,如下:


<plug-in className="net.sf.struts.saif.SAIFPlugin">
< set-property property="interceptor-config" value="/WEB-INF/interceptor-config.xml" />
< /plug-in>

最后,编写interceptor-config.xml文档,进行相关拦截器的声明,这样您就完成SAIF的安装和设定,下面我们将以一个现时的例子来阐述SAIF的使用及其长处。

我们现在有这个一个需求,在OA中,拟定人能够修改自己发的通知,其他人均不能修改,只能查看。我们撰写了两个ActionEditNoticeActionViewNoticeAction,我们传给这两个Action的参数时通知的编码:noticeId。通知对象的代码如下(HibernatePO方式):


public class NoticePO
{
private Integer id; //编码
private String title; //标题
private String content; //内容
private Integer authorId; //发布人编码
private Date publishedDate; //发布日前

//getter and setter methods
……….
}

同时我们拥有两个jsp文档:viewnotice.jspeditnotice.jsp,这样我们在Action中根据noticeIdNoticePO构建出来,然后传给jsp页面,jsp负责将数据显示出来,这样的流程就完毕啦。但是我们在实现中忘记了这个一点,权限的设定。所以我们需要对EditNoticeAction进行拦截操作,也就是在EditNoticeAction操作完毕后,将session中的用户idNoticePO中的authorId进行对比,假如相同,表示是该通知的拟定人,指向editnotice.jsp页面,否则,指向viewnotice.jsp页面。新建EditNoticeInterceptor,实现如下:


public class EditNoticeInterceptor extends DefaultInterceptor
{
public ActionForward afterAction(Action action, ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException
{
Integer userId=(Integer)request.getSession().getAttribute(“User_ID”);
NoticePO notice=( NoticePO)request.getAttribute(“notice”);
if(notice.getAuthorId()==userId)
{
return mapping.findForward(“view”);

return null;
}
}

这样我们就完成了拦截器的代码编写,下面就是在interceptor-config.xml对拦截器进行声明。


< ?xml version="1.0" encoding="gb2312"?>
< !DOCTYPE interceptor-config SYSTEM "http://struts.sourceforge.net/saif.dtd">
< interceptor name="EditNoticeActionInterceptor" 
type="net.jetmaven.interceptor.EditNoticeActionInterceptor"/>
<action type="net.jetmaven.action.EditNoticeAction">
< interceptor name="EditNoticeActionInterceptor"/>
< /action>
< /interceptor-config>

这样我们就完成了我们既定的需求,通过介入拦截器完全地将权限和业务逻辑分开啦。

最后再说说SAIFSAIF默认的拦截方法没有返回值,而在这里我们使用ActionForward作为返回值,目的就是想更改原先的流程,返回值为空表示继续原先流程,返回值不为空标识修改以前的流程,这样觉得更容易理解点,和实际情况更贴切。SAIF的拦截器能够重叠使用,就是针对某一Action能够有多个拦截器,这一点也是很有用的,我们同样更加返回值来判定是否终止这个链,假如返回值为空,标识继续该链,否则终止该链,立即返回。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值