SpringBoot之拦截器

    大家知道,框架中的拦截器就是用来拦截用户的请求,检查用户的每一个请求是否合法。那么我们基于SpringBoot框架,如何来使用拦截器呢?

1.定义拦截器

继承HandlerInterceptorAdapter类,该接口有三个方法,分别如下:

a.preHandle(用得比较多):预处理回调方法,实现处理器的预处理(如登录检查)

    返回值:

        true - 表示继续流程(如调用下一个拦截器或处理器);

        false - 表示流程中断(如登录检查失败),不会继续调用其他的拦截器或处理器,此时我们需要通过response来产生响应;

b.postHandle:后处理回调方法,实现处理器的后处理(但在渲染视图之前),此时我们可以通过modelAndView(模型和视图对象)对模型数据进行处理或对视图进行处理,modelAndView也可能为null;

c.afterCompletion:整个请求处理完毕回调方法,即在视图渲染完毕时回调。

2.注册拦截器

添加拦截器配置类,继承WebMvcConfigurerAdapter类,使用@Configuration注解;注册一个或多个拦截器,多个拦截器便构成了拦截器链,执行顺序按注册的先后顺序执行。

3.拦截器使用实例(登录验证)

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;

import org.apache.shiro.session.Session;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

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

import com.alibaba.fastjson.JSON;

public class AuthInterceptor extends HandlerInterceptorAdapter {

private static final Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

@Override

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)

throws Exception {

logger.info("The request URL is: {}", request.getRequestURL());

Session session = SecurityUtils.getSubject().getSession();

logger.info("客户传递过来的session是:{}",session.getId().toString());

if ((Long) session.getAttribute("uid") != null || ((UserInfo) session.getAttribute("user")) != null) {

return true;

}else {

logger.info("你还没有登录,暂无访问权限");

// 向客户端输出提示信息

response.setContentType("application/json;charset=utf-8");

response.getWriter().write(JSON.toJSONString(new CommonResponseDataVo("你还没有登录,暂无访问权限",

SuccessFailEnum.FAIL.getCode(), SuccessFailEnum.FAIL.getMsg())));

return false;

}

}

}

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration

public class InterceptorConfig extends WebMvcConfigurerAdapter {

// 注册自定义的拦截器类

@Override

public void addInterceptors(InterceptorRegistry registry) {

// 加入自定义拦截器AuthInterceptor,可添加多个

registry.addInterceptor(new AuthInterceptor()).addPathPatterns("需要拦截的请求url");

//registry.addInterceptor("不同的拦截器").addPathPatterns("需要拦截的请求url");

super.addInterceptors(registry);

}

}

猜你喜欢

转载自williamwhj.iteye.com/blog/2355352