zoukankan      html  css  js  c++  java
  • java后台解决跨域问题

    解决跨域问题的方式有很多,这里主要是添加注解的方式和采用添加拦截器的方法:

    方法一、spring boot中只用在Controller类上添加一个“@CrossOrigin“注解就可以实现对当前controller 的跨域 访问了,当然这个标签也可以加到方法上。

    @CrossOrigin
    public class CommonController {
    
    }

    其他controller类继承以上这个类就可以解决跨域问题。

    注意:“@CrossOrigin“注解要求jdk1.8以上版本

    方法二、采用添加拦截器的方法

    @Configuration
    public class WebConfig extends WebMvcConfigurerAdapter {
        @Autowired
        private EnvConfig envConfig;
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new HandlerInterceptor() {
                @Override
                public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                        throws Exception {
                    boolean isTrue = envConfig.getIsDev();//判断是测试服才需要解决跨域问题
                    if (isTrue) {
                        response.addHeader("Access-Control-Allow-Origin", "*");
                 response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); response.addHeader(
    "Access-Control-Allow-Headers", "Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,token"); } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }); }
    }
  • 相关阅读:
    VC 常见问题百问
    python windows 环境变量
    Check server headers and verify HTTP Status Codes
    Where are the AES 256bit cipher suites? Please someone help
    outlook 如何预订会议和会议室
    安装Axis2的eclipse插件后,未出现界面
    windows 环境变量
    python 时间日期处理汇集
    openldap学习笔记(使用openldap2.3.32)
    set p4 environment in windows
  • 原文地址:https://www.cnblogs.com/ouyanxia/p/8462997.html
Copyright © 2011-2022 走看看