先创建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方法