springboot 实现拦截器功能

先创建springboot 项目,结构如下


Controller控制器的hello方法为我们要访问的目标方法

package com.example.demo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by bingege on 2018/3/9.
 */
@RestController
public class Controller {
    @RequestMapping(value="/")
    public String Hello(){
        return "hello";
    }
}

InterceptorUtil 是我们自定义的拦截器,实现springboot的HandlerInterceptor方法,其中preHandle是在请求处理之前调用的,此文就是用此方法进行简单的拦截

package com.example.demo;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * Created by bingege on 2018/3/9.
 */
public class InterceptorUtil implements HandlerInterceptor {
    /**
     * todo : 在请求处理之前调用,此处当userId==chb时才能正常进入控制器,否则被拦截
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String userId = httpServletRequest.getParameter("userId");
        if("chb".equals(userId))
            return  true;
        else
            return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

最后我们还需要将我们自定义拦截器注入到spring中

package com.example.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * Created by bingege on 2018/3/9.
 */
@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
    @Bean   //把拦截器注入为bean
    public HandlerInterceptor getMyInterceptor(){
        return new InterceptorUtil();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getMyInterceptor()).addPathPatterns("/**");
        super.addInterceptors(registry);
    }
}

到此,自定义拦截器完成了。看看效果,当userId=chb时正常访问


当userId=ljc时,不能访问到我们的hello方法



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值