spring boot 拦截器 示例

我的梦境 提交于 2020-01-01 18:34:54

一、MVC配置类  WebMvcConfig 

 1、spring启动加载

package com.seven.mobile.uom.main.config;import com.alibaba.fastjson.serializer.SerializerFeature;import com.alibaba.fastjson.support.config.FastJsonConfig;import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;import com.github.pagehelper.PageHelper;import com.seven.mobile.uom.api.interceptor.AuthenticationInterceptor;import com.seven.mobile.uom.main.fastjson.CustomSerializeConfig;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.MediaType;import org.springframework.http.converter.HttpMessageConverter;import org.springframework.ldap.core.LdapTemplate;import org.springframework.ldap.core.support.LdapContextSource;import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;import java.util.ArrayList;import java.util.List;import java.util.Properties;/** * class_name: WebMvcConfig * package: com.seven.mobile.uom.main.config * describe: MVC配置类 * @author: yezh5 * @date: 2017/11/25 * @time: 20:15**/@Configurationpublic class WebMvcConfig extends WebMvcConfigurerAdapter {    private final static Logger logger = LoggerFactory.getLogger(WebMvcConfig.class);    /**     * LDAP 工具     * @param url     * @param username     * @param password     * @return     */    @Bean    public LdapTemplate ldapTemplate(@Value("${ldap.provider.url}") String url, @Value("${ldap.security.userDn}") String username,                                     @Value("${ldap.security.password}") String password) {        LdapContextSource contextSource = new LdapContextSource();        contextSource.setUrl(url);        contextSource.setUserDn(username);        contextSource.setPassword(password);       // contextSource.setBase(base);        // 是否启用线程池        contextSource.setPooled(true);        // 应用配置        contextSource.afterPropertiesSet();        return new LdapTemplate(contextSource);    }    /**     * 方法级验证     * @return     */    @Bean    public MethodValidationPostProcessor methodValidationPostProcessor() {        return new MethodValidationPostProcessor();    }    //配置mybatis的分页插件pageHelper    @Bean    public PageHelper pageHelper(){        System.out.println("MyBatisConfiguration.pageHelper()");        PageHelper pageHelper = new PageHelper();        Properties properties = new Properties();        properties.setProperty("offsetAsPageNum","true");        properties.setProperty("rowBoundsWithCount","true");        properties.setProperty("reasonable","true");        /**         * 配置mysql数据库的方言         */        properties.setProperty("dialect","mysql");        pageHelper.setProperties(properties);        return pageHelper;    }    /**     * 添加拦截器配置     * @return     */    @Override    public void addInterceptors(InterceptorRegistry registry) {        registry.addInterceptor(authenticationInterceptor()).addPathPatterns("/api/**");    }    @Bean    public AuthenticationInterceptor authenticationInterceptor() {        return new AuthenticationInterceptor();    }    /**     * fastjson相关配置     *     * @return     */    private FastJsonConfig getFastJsonConfig() {        logger.info("getFastJsonConfig.....");        FastJsonConfig fastJsonConfig = new FastJsonConfig();        //serializerFeatureList中添加转换规则        List<SerializerFeature> serializerFeatureList = new ArrayList<SerializerFeature>();        //输出key时是否使用双引号        serializerFeatureList.add(SerializerFeature.QuoteFieldNames);        //是否输出值为null的字段        serializerFeatureList.add(SerializerFeature.WriteMapNullValue);        //数值字段如果为null,输出为0,而非null        serializerFeatureList.add(SerializerFeature.WriteNullNumberAsZero);        //List字段如果为null,输出为[],而非null        serializerFeatureList.add(SerializerFeature.WriteNullListAsEmpty);        //字符类型字段如果为null,输出为"",而非null        serializerFeatureList.add(SerializerFeature.WriteNullStringAsEmpty);        //Boolean字段如果为null,输出为false,而非null        serializerFeatureList.add(SerializerFeature.WriteNullBooleanAsFalse);        //null String不输出        serializerFeatureList.add(SerializerFeature.WriteNullStringAsEmpty);        //Date的日期转换器        serializerFeatureList.add(SerializerFeature.WriteDateUseDateFormat);        SerializerFeature[] serializerFeatures =                serializerFeatureList.toArray(new SerializerFeature[serializerFeatureList.size()]);        fastJsonConfig.setSerializerFeatures(serializerFeatures);        fastJsonConfig.setSerializeConfig(new CustomSerializeConfig());        return fastJsonConfig;    }    /**     * fastJson相关设置     */    private FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {        logger.info("fastJsonHttpMessageConverter........");        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();        List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();        supportedMediaTypes.add(MediaType.parseMediaType("text/plain;charset=utf-8"));        supportedMediaTypes.add(MediaType.parseMediaType("text/html;charset=utf-8"));        supportedMediaTypes.add(MediaType.parseMediaType("text/json;charset=utf-8"));        supportedMediaTypes.add(MediaType.parseMediaType("application/json;charset=utf-8"));        supportedMediaTypes.add(MediaType.parseMediaType("text/html;charset=utf-8"));        supportedMediaTypes.add(MediaType.parseMediaType("*"));        fastJsonHttpMessageConverter.setSupportedMediaTypes(supportedMediaTypes);        fastJsonHttpMessageConverter.setFastJsonConfig(getFastJsonConfig());        return fastJsonHttpMessageConverter;    }    /**     * 添加fastJsonHttpMessageConverter到converters     */    @Override    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {        logger.info("configureMessageConverters........");        converters.add(fastJsonHttpMessageConverter());    }    @Override    public void addResourceHandlers(ResourceHandlerRegistry registry) {        registry.addResourceHandler("swagger-ui.html")                .addResourceLocations("classpath:/META-INF/resources/");        registry.addResourceHandler("/webjars/**")                .addResourceLocations("classpath:/META-INF/resources/webjars/");    }}

二、AuthenticationInterceptor    CLASS

1、登录过滤

2、验证接口请求中的token

/** Copyright (c) 2017 seven.com. All Rights Reserved.*/package com.seven.mobile.uom.api.interceptor;import com.alibaba.fastjson.JSONObject;import com.alibaba.fastjson.serializer.SerializerFeature;import com.seven.mobile.uom.common.model.SysUserDO;import com.seven.mobile.uom.common.response.BaseResponse;import com.seven.mobile.uom.common.response.ResponseCode;import com.seven.mobile.uom.common.response.StatusCode;import com.seven.mobile.uom.common.service.RedisService;import com.seven.mobile.uom.common.util.RequestHolder;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.method.HandlerMethod;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.PrintWriter;import static com.seven.mobile.uom.common.constant.LoginConstant.*;/** * <p> * token校验拦截器 * </p> * @author  * @date 2017-12-07 */public class AuthenticationInterceptor implements HandlerInterceptor {    @Autowired    private RedisService redisService;    private static final String LOGIN_URL="login/login";    @Override    public boolean preHandle(HttpServletRequest request,                             HttpServletResponse response, Object handler) throws Exception {        // 如果不是映射到方法直接通过        if (!(handler instanceof HandlerMethod)) {            return true;        }       // 如果是映射到登陆方法直接通过        String url = request.getRequestURI();        if(url.contains(LOGIN_URL)){            return true;        }        // 从 http 请求头中取出 token,取不到返回false        String token = request.getHeader(ACCESS_TOKEN);        if (token == null) {            resultInfo(response,ResponseCode.NO_TOKEN);            return false;        }        // 根据token去缓存中验证        Object sysUserDO=redisService.get(LOGIN_TOKENS,token);        if(null!=sysUserDO){            SysUserDO sysUser=(SysUserDO)sysUserDO;            RequestHolder.add(sysUser);            RequestHolder.add(request);            return true;        }else{            resultInfo(response,ResponseCode.TOKEN_ERROR);            return false;        }    }    @Override    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {        removeThreadLocalInfo();    }    @Override    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {        removeThreadLocalInfo();    }    public void removeThreadLocalInfo() {        RequestHolder.remove();    }
/** * token为null  返回处理 * @param response * @param code * @throws Exception */
   private void resultInfo(HttpServletResponse response, StatusCode code) throws Exception {        BaseResponse resp = new BaseResponse();        resp.setCode(code);        response.setContentType("application/json;charset=UTF-8") ;        PrintWriter writer = response.getWriter();        writer.write(JSONObject.toJSONString(resp, SerializerFeature.WriteEnumUsingToString));        writer.flush();        writer.close();    }}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!