异步请求
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);
//内置过滤器配置完成