欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

十三、springBoot 配置自定义拦截器

程序员文章站 2022-07-03 20:05:55
...

1、自定义拦截器,实现HandlerInterceptor或者继承WebMvcConfigurerAdapter

import com.alibaba.fastjson.JSON;
import com.trgis.www.manage.entity.TRUser;
import com.trgis.www.manage.service.TRUserService;
import com.trgis.www.util.BeanUtil;
import com.trgis.www.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * @Author: zhao
 * @CreateDate: 2019/10/17$ 18:57$
 */
@Controller
public class UserTokenInterceptor implements HandlerInterceptor{

    @Autowired
    private TRUserService trUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        TRUser user = (TRUser) session.getAttribute("user");
        if (BeanUtil.isEmpty(user)) {
            Result result = new Result();
            result.setError("登录超时", -1);
            returnResult(result, response);
            return false;
        } else {
            Result result = new Result();
            String username = user.getUsername();
            TRUser trUser = trUserService.findByUsername(username);
            if (BeanUtil.isNotEmpty(trUser)) {
                if (!trUser.getPassword().equals(user.getPassword())) {
                    result.setError("用户密码已更改");
                    returnResult(result, response);
                    return false;
                }
            } else {
                result.setError("用户不存在");
                returnResult(result, response);
                return false;
            }
        }
        return true;
    }

    private void returnResult(Result result, HttpServletResponse response) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        String json = JSON.toJSONString(result);
        try {
            writer = response.getWriter();
            writer.print(json);
        } catch (Exception e) {

        } finally {
            if (null != writer) {
                writer.close();
            }
        }
    }
}

2、配置静态资源、以及自定义拦截器对部分接口不拦截,配置如下

import com.trgis.www.framework.interceptor.UserTokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * @Author: zhao
 * @CreateDate: 2019/10/17$ 18:50$
 */
@Component
public class WebMvcConfig extends WebMvcConfigurationSupport{

    @Autowired
    private UserTokenInterceptor userTokenInterceptor;

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        //第一个方法设置访问路径前缀,第二个方法设置资源路径
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(userTokenInterceptor)
                //addPathPatterns 用于添加拦截规则
                .addPathPatterns("/**")
                //项目启动测试接口
                .excludePathPatterns("/")
                // 静态资源
                .excludePathPatterns("/static/**")
                // SwaggerUI
                .excludePathPatterns("/swagger-ui.html","/v2/api-docs","/webjars/**","/swagger-resources/**")
                // 用户登录不拦截
                .excludePathPatterns("/login")
                // public为前缀的访问都取消验证
                .excludePathPatterns("/public/**");

    }
}