springboot自定义拦截器

1,创建一个TokenInterceptor实现HandlerInterceptor

package com.dagen.imgs.config.se;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Method;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    private SecurityHandler securityHandler;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if ("OPTIONS".equals(request.getMethod())){
            return true ;
        }
        HandlerMethod hm = (HandlerMethod) handler;
        Method method = hm.getMethod();
        if (method.isAnnotationPresent(SecuritySkip.class)) {
            SecuritySkip annotation = method.getAnnotation(SecuritySkip.class);//获取value
            //System.out.println(annotation.value());
            return true;
        }
        if (method.getDeclaringClass().isAnnotationPresent(SecuritySkip.class)) {
            SecuritySkip annotation = method.getDeclaringClass().getAnnotation(SecuritySkip.class);
           // System.out.println(annotation.value());
            return true;
        }
       // try {

            return securityHandler.checkToken(request);
       /* } catch (SysException e) {
            ResultBody body = new ResultBody(ResultBody.FAILED, e.getMessage());
            response.setCharacterEncoding("UTF-8");
            response.getWriter().println(body.toJson());
        }
        return false;*/
    }


}

2,按照自己的需求处理

package com.dagen.imgs.config.se;


import com.dagen.imgs.dao.UserDao;
import com.dagen.imgs.pojo.Dto.PermissionDto;
import com.dagen.imgs.pojo.PermissionPo;
import com.dagen.imgs.pojo.UserBackPo;
import com.dagen.imgs.pojo.UserPo;
import com.dagen.imgs.util.UserBaskUtil;
import com.dagen.imgs.util.UserUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Component
public class SecurityHandler {

    @Resource
    private UserBaskUtil userBaskUtil;

    @Resource
    private UserDao userDao;

    private String findToken(HttpServletRequest request) {
        String tokenName = "NS-Session";
        String token = request.getHeader(tokenName);
        if (StringUtils.isEmpty(token)) {
            throw new SysException("接口未授权");
        }

        return token;
    }

    private void checkToken(String token,String role) {
        if (StringUtils.isEmpty(token)) {
            throw new SysException("接口未授权");
        }
        UserBackPo po = userBaskUtil.getUserCaInfo(token);
        if (po == null) {
            throw new SysException("接口未授权");
        }
        List<String> list = userDao.findPermission(po.getId());
        if (!list.contains(role)) {
            throw new SysException("接口未授权");
        }
    }

    /**
     * 设置 Token
     *
     * @param admin admin 数据
     * @return token
     * @throws Exception 异常统一处理
     */
   /* public String setToken(UserDto admin) throws Exception {
        String key = Base64.getEncoder().encodeToString(Md5Util.md5Digest(admin.getPassword() + admin.getUsername()
                + System.currentTimeMillis()).getBytes(StandardCharsets.UTF_8));
        String data = admin.toJson();
        redisService.set(RedisKey.ADMIN_TOKEN_KEY.value() + key, data, "1h");
        return key;
    }*/

    /**
     * 从 Request 检测 Token
     *
     * @param request HttpServletRequest
     */
    public Boolean checkToken(HttpServletRequest request) {

        String token = this.findToken(request);
        String url = request.getRequestURI();//获取路径
        String role = "";
        role = url.contains("/ordersBack") ? "ORDER" : url.contains("/otherBack") ? "OTHER" : url.contains("/SourceBack") ? "MATERIAL" : url.contains("/Website") ? "DESIGN" : "";
        if (StringUtils.isEmpty(role)) {
        }
        this.checkToken(token,role);

        return true;
    }

    public void delToken(HttpServletRequest request) {
        String token = this.findToken(request);
        userBaskUtil.delUserCaInfo(token);
    }

    /**
     * 设置 Session
     *
     * @param model   用户数据
     * @param request request
     */
   /* public void setSession(UserModel model, HttpServletRequest request) {
        String sessionId = request.getSession().getId();
        String key = RedisKey.USER_SESSION_KEY.value() + sessionId;
        redisService.set(key, model.toJson(), "7d");
    }*/

    /**
     * 从request 检测 session
     *
     * @param request request
     */
/*    public void checkSession(HttpServletRequest request) {
        String sessionId = request.getSession().getId();
        String key = RedisKey.USER_SESSION_KEY.value() + sessionId;
        String json = (String) redisService.get(key);
        UserInfoModel model = new Gson().fromJson(json, UserInfoModel.class);
        if (model == null) {
            throw new SysException("请先登陆");
        }
    }*/

}

定义一个注解类来控制那些需要权限

package com.dagen.imgs.config.se;

import java.lang.annotation.*;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface SecuritySkip {

   // String value() default "SB";
}

添加拦截器

package com.dagen.imgs.config.se;

import com.dagen.imgs.support.wechat.NsInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

import javax.annotation.Resource;

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    @Resource
    private TokenInterceptor tokenInterceptor;
    @Autowired
    private NsInterceptor nsInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        System.out.println("添加拦截器");
        registry.addInterceptor(tokenInterceptor).addPathPatterns("/**").excludePathPatterns("/v1/notify")
        .excludePathPatterns("/index.html").excludePathPatterns("/webSocket.html");
        registry.addInterceptor(nsInterceptor).addPathPatterns("/v1/notify");
        WebMvcConfigurer.super.addInterceptors(registry);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //文件磁盘图片url 映射
        //配置server虚拟路径,handler为前台访问的目录,locations为files相对应的本地路径
        //registry.addResourceHandler("/img/**").addResourceLocations("file:///home/img/");
        registry.addResourceHandler("/img/**").addResourceLocations("file:///D:/imgs/");
        WebMvcConfigurer.super.addResourceHandlers(registry);
    }
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "PUT", "OPTIONS", "DELETE")
                .maxAge(3600);
        WebMvcConfigurer.super.addCorsMappings(registry);
    }

}

定义一个全局捕获异常

package com.dagen.imgs.config.se;


import com.aliyun.oss.ServiceException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常捕获
 */
@ControllerAdvice
public class MyException {
    @ExceptionHandler(value = SysException.class)
    @ResponseBody
    public Map SysException(Throwable e){
        e.printStackTrace();
        Map map=new HashMap();
        map.put("res",-6);
        map.put("message","你没有这个权限!");
        return map;
    }
    @ExceptionHandler(value = SeException.class)
    @ResponseBody
    public Map SeException(SeException e){
        Map map=new HashMap();
        map.put("res",-2);
        map.put("message",e.getMessage());
        return map;
    }
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Map Exception(Exception e){
        e.printStackTrace();
        Map map=new HashMap();
        map.put("res",-3);
        map.put("message","系统异常!");
        return map;
    }
}

自己用的返回工具类

package com.dagen.imgs.config.se;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import com.google.gson.Gson;
import lombok.Data;

import java.io.Serializable;

/**
 * API 接口结果
 *
 * @author Nico Jiang
 */
@Data
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class ResultBody implements Serializable {

    private static final long serialVersionUID = -586264308558755306L;

    public static final String SUCCESS = "0";
    public static final String FAILED = "1";

    private String resultCode;
    private String resultMsg;
    private Object resultData;

    public ResultBody() {
    }

    public ResultBody(String resultCode, String resultMsg) {
        this.resultCode = resultCode;
        this.resultMsg = resultMsg;
    }

    public static ResultBody build() {
        return new ResultBody(SUCCESS, "SUCCESS");
    }

    public String toJson() {
        return new Gson().toJson(this);
    }

}

代码粘贴了一下,里面的业务需要按照自己需求改动,不懂的可以加我Q1689826485一起探讨

你可能感兴趣的:(springboot自定义拦截器)