struts2中拦截器(interceptor)的简单配置

来源:互联网 发布:sqlyog怎么写sql语句 编辑:程序博客网 时间:2024/05/21 06:50

拦截器

在struts2中应用的拦截器,个人理解,就是从servlet的filter过滤器引用过来的,然后再加以封装,应用到了struts2中。**注意:拦截器只拦截/过滤对action的请求**配置了interceptor,则在访问action之前,先要经过拦截器的验证。还是直接上例子吧!!!

第一步:自定义intercept类

这个类继承interceptor接口,重写三个方法,在  intercept(ActionInvocation invoke)方法中,自定义逻辑,--------invoke.invoke()执行请求的actionreturn invoke.invoke()可以把action的执行结果返回给action的result标签。-------------------------------------------------------------interceptor类,一般都要实现 interceptor接口,如果不实现,虽然报错,但是仍然能上传成功(亲测过..)----------------------------------------------public class UpLoadInterceptor{public String intercept(ActionInvocation invoke) throws Exception {    // TODO Auto-generated method stub    String type = ServletActionContext.getRequest().getParameter("type");    System.out.println("start interceptor..");    System.out.println("type:"+type);    if (type.equals("1") ) {                String m =invoke.invoke();        System.out.println(m);        return m;    }    return "fail";}}

报错:
Caused by: Class [interceptor.UpLoadInterceptor] does not implement Interceptor - interceptor

-file:/D:/Tomcat/apache-tomcat-8.5.14/webapps/UpLoadAndDownLoad/WEB-

INF/classes/struts.xml:10:77


第二步:struts.xml配置文件:

<interceptors>    <interceptor name="myInterceptor"    class="interceptor.UpLoadInterceptor"/><interceptor-stack name="myStack">    <interceptor-ref name="myInterceptor"/>    <interceptor-ref name="defaultStack"/></interceptor-stack></interceptors><default-interceptor-ref name="myStack"></default-interceptor-ref><action name="upLoadAction" class="action.UpLoadAction"         method="upLoad">            <result name="success">/main.jsp</result><result name="fail">/login.jsp</result></action>

如果设置了默认拦截器default-interceptor-ref,再给action配置一个interceptor,则配置给action的发生作用(就近原则?)<interceptors><interceptor name="myInterceptor" class="interceptor.UpLoadInterceptor"/><interceptor name="myInterceptor1" class="interceptor.UpLoadInterceptor1"/><interceptor-stack name="myStack">    <interceptor-ref name="myInterceptor"/>    <interceptor-ref name="defaultStack"/></interceptor-stack><interceptor-stack name="myStack1">    <interceptor-ref name="myInterceptor1"/>    <interceptor-ref name="defaultStack"/></interceptor-stack></interceptors><default-interceptor-ref name="myStack"></default-interceptor-ref><action name="upLoadAction" class="action.UpLoadAction" method="upLoad"><interceptor-ref name="myStack1"/>          <result name="success">/main.jsp</result><result name="fail">/login.jsp</result></action>

第三步:前端页面设置:

按照正常的访问action配置。

第四步:亲手测试

原创粉丝点击