概述
1.通过Javabean定义一个拦截器,需实现HandlerInterceptor接口并重写三个方法(在这只实现拦截前操作)
public class UserInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object user = request.getSession().getAttribute("user");
if(user == null){
response.sendRedirect(request.getContextPath()+"/user/nologin");
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
在preHandle方法中定义拦截器功能,返回true表示放行,false表示拦截(可通过response.sendRedirect(request.getContextPath()+"/user/nologin")方法重定向URL)
2.通过配置文件对拦截器进行配置(取消xml文件形式,使用配置类)
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
String[] allow = {"/user/**"};
String[] noAllow = {"/user/nologin","/user/login"};
registry.addInterceptor(new UserInterceptor()).addPathPatterns(allow).excludePathPatterns(noAllow);
WebMvcConfigurer.super.addInterceptors(registry);
}
}
registry.addInterceptor()用于指定拦截器类 addPathPatterns()方法可存放String类型数组,用于指定需要拦截的URL excludePathPatterns()方法可存放String类型数组,用于指定不需要拦截的URL
3.测试控制器
@Controller
@RequestMapping(value = "/user")
public class InterceptorController {
@RequestMapping(value = "/login")
@ResponseBody
public String login(HttpServletRequest request){
User user = new User("zhangsan",55,66,77);
request.getSession().setAttribute("user",user);
return "login success";
}
@RequestMapping(value = "/nologin")
@ResponseBody
public String nologin(){
return "login false";
}
@RequestMapping(value = "/enter")
@ResponseBody
public String enter(){
return "enter success";
}
}
ps:不需要单独进行其他配置即可自定义拦截器
最后
以上就是俊逸西装为你收集整理的springboot Interceptor拦截器设置的全部内容,希望文章能够帮你解决springboot Interceptor拦截器设置所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复