spring boot 学习手册
  • 介绍
  • 基础教程
    • 1.RESTfull API简单项目的快速搭建
    • 2.配置文件详解:Properties和YAML
    • 3.配置文件-多环境配置
    • 4.日志配置-logback和log4j2
  • web应用开发
    • 1.模板引擎
    • 2.模板引擎FreeMarker
    • 3.模板引擎Thymeleaf
    • 4.模板引擎jsp
    • 5.错误处理
    • 6.Servlets, Filters, listeners
    • 7.CORS支持
    • 8.文件上传
    • 9.Interceptor拦截器
    • 10.AOP统一处理Web请求日志
    • 11.全局统一异常处理
    • 12. Retry重试
    • 13.RestTemplate
  • 关系型数据库
    • 1.JdbcTemplate
    • 2.Spring-data-jpa
      • @Id 和 @GeneratedValue 详解
      • 配置与注解备注
      • 全局统一前缀策略
      • 映射关系详解
      • 查询、分页、排序
      • JPA 资料
      • 进阶:jpa自定义行为方法
      • 进阶:锁
      • 进阶:Hibernate Validator
    • 3.事务处理
  • NoSQL数据库
    • 1.Redis
    • 2.Mongodb
  • Cache
    • 1.EhCache
    • 2.Redis
  • 异步消息服务
    • 1.JMS(ActiveMQ)
    • 2.AMQP(RabbitMQ)
  • Mybatis
    • Mybatis 初使用
    • Mybatis环境搭建
    • Mybatis开发流程
    • 业务开发流程
    • Mybatis资料
  • 进阶
    • 1.调用REST服务-使用代理
    • 2.发送邮件
    • 3.Spring Session实现集群-redis
    • 4.如何进行远程调试
    • 5.生产准备-基于HTTP的监控
    • 6.Spring Boot集成mybatis
    • 7.Spring Boot集成Druid
    • 8.Spring Boot集成Swagger
    • 9.生产部署-注意事项和如何使用脚本
  • 升华
    • Jenkins部署Spring Boot
    • 异步处理Http请求
    • FastDFS
    • Docker
    • 定时任务(corn job)
    • 批处理
    • @Async实现异步调用
  • 单元测试
    • WireMock伪造服务
  • 安全
    • 1.Spring Security
      • 认证
    • 2.Apache Shiro
  • TaskExecutor 异步线程池
  • 其他
    • 1.修改启动时显示
    • 2.获取配置文件中的值
    • 3.嵌入式容器
    • 4.配置SSL
    • 5.websocket
    • 6.Spring IO Platform
  • RESTfull API 开发
  • 附录:Eclipse - Spring Tool Suite工具的安装
  • 附录:Eclipse部署Maven
  • 附录:SpringBoot相关模块
  • 附录:注解笔记
  • 资料
  • 开发技巧
  • maven插件
Powered by GitBook
On this page
  • 一、Web 开发经常会遇到跨域问题,解决方案有:jsonp,iframe,CORS 等等 CORS 与 JSONP 相比
  • 二、在 spring MVC 中可以配置全局的规则,也可以使用@CrossOrigin 注解进行细粒度的配置。
  • 资料

Was this helpful?

  1. web应用开发

7.CORS支持

一、Web 开发经常会遇到跨域问题,解决方案有:jsonp,iframe,CORS 等等 CORS 与 JSONP 相比

1、JSONP 只能实现 GET 请求,而 CORS 支持所有类型的 HTTP 请求。

2、使用 CORS,开发者可以使用普通的 XMLHttpRequest 发起请求和获得数据,比起 JSONP 有更好的错误处理。

3、JSONP 主要被老的浏览器支持,它们往往不支持 CORS,而绝大多数现代浏览器都已经支持了 CORS

浏览器支持情况

  • Chrome 3+

  • Firefox 3.5+

  • Opera 12+

  • Safari 4+

  • Internet Explorer 8+

二、在 spring MVC 中可以配置全局的规则,也可以使用@CrossOrigin 注解进行细粒度的配置。

全局配置:

@Bean
    public WebMvcConfigurer corsConfigurer() {

        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");
            }
        };
    }

或者使用下面的方式

@Configuration
public class CustomCorsConfiguration2 extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");
    }
}

具体实现:

CustomCorsConfiguration.java

package com.shuju.example.util.configuration;

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

@Configuration
public class CustomCorsConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {

        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**").allowedOrigins("http://localhost:8080");
            }
        };
    }
}

ApiController.java

package com.shuju.example.controller;

import java.util.HashMap;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping(value = "/api", method = RequestMethod.POST)
public class ApiController {

    @RequestMapping(value = "/get")
    public HashMap<String, Object> get(@RequestParam String name) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("title", "hello world");
        map.put("name", name);
        return map;
    }
}

启动测试:

可以通过其他程序进行ajax请求测试

 $.ajax({
        url: "http://localhost:8080/api/get",
        type: "POST",
        data: {
            name: "测试"
        },
        success: function(data, status, xhr) {
            console.log(data);
            alert(data.name);
        }
    });

也可以使用postmans发送post测试

细粒度配置:

@CrossOrigin 注释

直接加在controller

package com.shuju.example.controller;

import java.util.HashMap;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

//  @CrossOrigin 所有的controller都支持
@RestController
@RequestMapping(value = "/api", method = RequestMethod.POST)
public class ApiController {
    @CrossOrigin(origins = "http://localhost:8080")
    @RequestMapping(value = "/get")
    public HashMap<String, Object> get(@RequestParam String name) {
        HashMap<String, Object> map = new HashMap<String, Object>(); map.put("title", "hello world");
        map.put("name", name);
        return map;
    }
}

资料

Previous6.Servlets, Filters, listenersNext8.文件上传

Last updated 5 years ago

Was this helpful?

WebMvcConfigurerAdapter 在Spring5.0已被废弃