spring boot 拦截器

springboot拦截器

1.编写拦截器

import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 处理跨域问题
 * User mz
 * date 2018/7/18
 */
public class CrossDomainInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}

 

2.编写拦截器配置文件

import com.idelan.highway.interceptor.CrossDomainInterceptor;
import com.idelan.highway.interceptor.GlobalInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * 拦截器配置
 * User mz
 * date 2018/6/25
 */
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter{

    @Bean
    public GlobalInterceptor getGlobalInterceptor() {
        return new GlobalInterceptor();
    }

    @Bean
    public CrossDomainInterceptor getCrossDomainInterceptor() {
        return new CrossDomainInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //跨域过滤
        registry.addInterceptor(getCrossDomainInterceptor()).addPathPatterns("/*/**");

        //验证是否登录过
        registry.addInterceptor(getGlobalInterceptor()).addPathPatterns("/*/**").excludePathPatterns("/detectionUser/login");
        super.addInterceptors(registry);
    }
}

 

posted @ 2018-07-18 15:58  谋知  阅读(139)  评论(0编辑  收藏  举报