Spring MVC异步请求和跨源资源共享(CORS)

异步请求

DeferredResult——延迟处理结果

@GetMapping("/quotes")
@ResponseBody
public DeferredResult<String> quotes() {
//创建延迟处理结果并返回
    DeferredResult<String> deferredResult = new DeferredResult<String>();
    // Save the deferredResult somewhere..
    return deferredResult;
}

// From some other thread...
//延迟处理结果,载入数据
deferredResult.setResult(data);

Callable

@PostMapping//拦截请求
public Callable<String> processUpload(final MultipartFile file) {

    return new Callable<String>() {
        public String call() throws Exception {//返回异步数据
            // ...
            return "someView";
        }
    };

}

CORS——跨资源共享

实现方式:

@CrossOrigin

/**
*三种情况,在类级别注解,将类级别注解拆分为类级别与方法级别注解,直接只在方法级别注解
*/
//或者1
@CrossOrigin(origins = "https://domain2.com", maxAge = 3600)
//或者2
@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {
     // 或者3
    @CrossOrigin
     //或者2
    @CrossOrigin("https://domain2.com")
    @GetMapping("/{id}")
    public Account retrieve(@PathVariable Long id) {
        // ...
    }

    @DeleteMapping("/{id}")
    public void remove(@PathVariable Long id) {
        // ...
    }
}

配置方式:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {

        registry.addMapping("/api/**")
            .allowedOrigins("https://domain2.com")
            .allowedMethods("PUT", "DELETE")
            .allowedHeaders("header1", "header2", "header3")
            .exposedHeaders("header1", "header2")
            .allowCredentials(true).maxAge(3600);

        // Add more mappings...
    }
}

或者

<mvc:cors>

    <mvc:mapping path="/api/**"
        allowed-origins="https://domain1.com, https://domain2.com"
        allowed-methods="GET, PUT"
        allowed-headers="header1, header2, header3"
        exposed-headers="header1, header2" allow-credentials="true"
        max-age="123" />

    <mvc:mapping path="/resources/**"
        allowed-origins="https://domain1.com" />

</mvc:cors>

CORS过滤器

//创建一个配置
CorsConfiguration config = new CorsConfiguration();

// Possibly...
// config.applyPermitDefaultValues()
//在配置中设置参数
config.setAllowCredentials(true);
config.addAllowedOrigin("https://domain1.com");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
//创建url配置源,用于映射
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
//将映射添加到过滤器中
CorsFilter filter = new CorsFilter(source);
//内置过滤器配置完成
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值