springboot 请求拦截器---含后端解决前端跨域问题

拦截器参考: https://www.jianshu.com/p/e52444f0a121

跨域参考: https://www.cnblogs.com/yuansc/p/9076604.html

 

 

 

创建一个Config来注册拦截器,代码如下:

MyMvcConfig    -----这个意义是 让配置的一些接口,不需要走拦截器的逻辑

package com.config;

import com.controle.lanjie.LoginHandlerInterceptor;
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.WebMvcConfigurer;

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    //所有的WebMvcConfigurerAdapter组件都会一起起作用
    @Bean //将组件注册在容器中
    public WebMvcConfigurer webMvcConfigurerAdapter(){
        return new WebMvcConfigurer(){

            //注册拦截器
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                //静态资源; *.css,*.js
                //SpringBoot已经做好了静态资源映射
                registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**");
//                .excludePathPatterns("/index.html","/","/user/login","/static/**","/webjars/**");
                // /**  表示拦截所有路径下的所有请求
//                registry.addInterceptor(new LoginHandlerInterceptor())
//                        .addPathPatterns("/person.html","/Person.html",
//                                "/questionnaire.html","/Questionnaire.html",
//                                "/result.html","/Result.html");
            }
        };
    }

}

 

 

创建一个拦截器

LoginHandlerInterceptor

package com.controle.lanjie;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {

    //目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //--------------------------------------------------------添加请求头,允许跨域----方法一
        setHeader(name, value):如果Header中没有定义则添加,如果已定义则用新的value覆盖原用value值。
        addHeader(name, value):如果Header中没有定义则添加,如果已定义则保持原有value不改变。
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        //Access-Control-Allow-Methods: 真实请求允许的方法
        //Access-Control-Allow-Headers: 服务器允许使用的字段
        //Access-Control-Allow-Credentials: 是否允许用户发送、处理 cookie
        //Access-Control-Max-Age: 预检请求的有效期,单位为秒。有效期内,不会重复发送预检请求
        
        
        //获取请求参数
        Object user5 = request.getQueryString();
        System.out.println(user5);
        //获取请求头参数
        Object user6 = request.getHeader("currentUser");
        System.out.println(user6);
        //获取请求方式
        Object user7 = request.getMethod();
        System.out.println(user7);
        //获取请求路径
        Object user8 = request.getRequestURI();
        System.out.println(user8);
        //重定向访问路径
        response.sendRedirect("/bbb2");
//        添加请求头
        response.addHeader("location","http://baidu.com");
//        if (user == null) {
//            //未登录,返回登录页面
//            System.out.println("第一拦截了,请求前");
////            response.sendRedirect("/LoginError.html");
//            return false;
//        }else {
//            //放行
            return true;
//        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        System.out.println("第二拦截了,请求中");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        System.out.println("第三拦截了,请求后");
    }
}

 

 

允许前端跨域方法二 ----添加全局配置类

package com.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    /**
     * 跨域支持
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .allowedHeaders("*")
				.maxAge(3600 * 24);
    }
}

 

还可以通过添加 Filter 的方式,配置 CORS 规则,并手动指定对哪些接口有效。---这个我没试过,上面2种亲测ok

@Bean
public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);    config.addAllowedOrigin("http://localhost:9000");
    config.addAllowedOrigin("null");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config); // CORS 配置对所有接口都有效
    FilterRegistrationBean bean = newFilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
}

 

 

三更草堂是向下面那样写的 亲测成功

bilibili.com/video/BV1U44y1W77D

package com.qingge.springboot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {

    // 当前跨域请求最大有效时长。这里默认1天
    private static final long MAX_AGE = 24 * 60 * 60;

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
        corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
        corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
        corsConfiguration.setMaxAge(MAX_AGE);
        source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
        return new CorsFilter(source);
    }
}

增加跨域配置解决的方法见 https://www.cnblogs.com/kaibindirver/p/16189077.html

posted @ 2021-11-09 01:13  凯宾斯基  阅读(1044)  评论(0编辑  收藏  举报