ssm 拦截器

第一种写法

<!-- 第一种写法(针对所有请求,都拦截) -->
<bean id="checklogin" class="com.k.util.LoginIntercepter"/>
<mvc:interceptors>
    <ref bean="checklogin" />
</mvc:interceptors>

第二种写法

<!-- 第二种写法 (与第一种写法效果一致,也是针对所有请求都拦截)-->
<mvc:interceptors>
    <bean class="com.k.util.LoginIntercepter"/>
</mvc:interceptors>

第三种写法

<!-- 第三种写法 -->

<mvc:interceptors>
    <mvc:interceptor>

    <!-- 用来指定拦截器拦截的范围
        /   代表根目录
        /*  表示根目录下的所有请求,但不包括子目录中的请求
        /** 表示所有请求,包括子目录中的请求也拦截
    -->
        <mvc:mapping path="/**"/>

        <!-- 拦截调用的类 -->
        <bean class="com.k.util.LoginIntercepter"/>
    </mvc:interceptor>
</mvc:interceptors>

执行的类

package com.k.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class LoginIntercepter extends HandlerInterceptorAdapter {


    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        System.out.println("LoginIntercepter --> preHandle方法执行了");
        String uri = request.getRequestURI();
        System.out.println("uri: " + uri);
        String contextpath = request.getContextPath();
        System.out.println("contextpath: " + contextpath);
        String requestname = uri.substring(contextpath.length() + 1, uri.length());
        System.out.println("requestname:" + requestname);
        String path = request.getContextPath();
        String besepath = request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort() + path + "/";
        System.out.println(besepath);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        System.out.println("业务方法执行之后要做的操作");
        System.out.println("LoginIntercepter --> postHandle 方法执行了");
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println("请求处理完成时要做的操作");
        System.out.println("LoginIntercepter --> afterCompletion 方法执行了");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值