作用域和自定义拦截器

一,访问request/session/application

如果在Action中,只需要往作用域中添加属性或者得到属性,就用以下的方法来得到:

    ActionContext act = ActionContext.getContext();

    act.put("username", "hwt");//request中添加属性

    act.get("username"); //取得request中的属性

    act.getSession().put("username", "hwt");//session中添加属性

    act.getSession().get("username");//取得session中的属性

    act.getApplication().put("username", "hwt");//application中添加属性

    act.getApplication().get("username");//取得application中的属性

 

如果需要得到request/session/application 对象的话,那么就用以下方法:

//得到Servlet容器

        ServletContext sc = ServletActionContext.getServletContext();

        //得到request对象

        HttpServletRequest request = ServletActionContext.getRequest();

        //得到response对象

        HttpServletResponse response = ServletActionContext.getResponse();

        //得到session对象

        HttpSessionsession = request.getSession();

 

二,自定义拦截器

1,写一个实现类,继承Interceptor

 

2,在struts.xml中配置

 

如:权限的拦截

public class UserInterceptor implements Interceptor {

    public void destroy() {

    }

    public void init() {

    }

    public String intercept(ActionInvocation method) throws Exception {

        HttpSession session = ServletActionContext.getRequest().getSession();

        User user = (String) session.getAttribute("user");

        if(user == null){

            return "failure"; //拦截请求,转向输出一个result页面

        }else {

            method.invoke(); //允许进入方法

        }

        return null;

    }

}

 

配置文件:

<package name="hwt" namespace="/hwt"extends="struts-default">

<interceptors>

<interceptor name="userIntercepter" class="hwt.Converter.UserInterceptor"/>

<! - - 定义拦截器栈,把默认的拦截器和自己写的拦截器结合起来 - - >

    <interceptor-stackname="myStack">

        <!—一定要加上defaultStack拦截器放在最后面-->

                <interceptor-ref name="userIntercepter"/>

<interceptor-ref name="defaultStack"/>

    </interceptor-stack>

</interceptors>

       

        <action name="test" class="hwt.action.Demo1Action"method="show">

            <!—如果把拦截器写在这个里面,那么进入这个Action后之后使用自己写的拦截器,不会使用默认的拦截器,但是默认的拦截器有很多强大的功能,如文件上传大小以及类型的控制,重复提交的控制等,所以我们在package中定义拦截器栈,放入系统的拦截器和自己写的拦截器-->

        </action>

    </package>

</struts>

 

如果希望包下的所有action都使用自定义的拦截器,可以通过<default-interceptor-ref name=“myIntercepterStack”/>,把拦截器定义为默认拦截器。

注意:每个包只能指定一个默认拦截器。另外,一旦我们为该包中的某个action显式指定了某个拦截器,则默认拦截器不会起作用。

 

默认的拦截器中的比较常用的拦截器:(后面会提到)

         fileUpload

         toKen

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值