一、可以在配置类中通过配置一个@Bean,直接实现全局的跨域,不需要在每个controller上加@CrossOrigin注解了。
package cn.edu.tju.config;
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;
@Configuration(proxyBeanMethods = false)
public class MyCorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
};
}
}
二、适用情况: 1、返回字符串或对象的接口
@RequestMapping("/getRate")
public String getRate(){
return "rate...";
}
2.通过ResponseEntity提供文件下载功能的接口
@RequestMapping(value="/get/csv")
public ResponseEntity<byte[]> download(HttpServletRequest request)throws Exception{
String content="first,second,third";
ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
builder.contentLength(content.length());
builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
String fileName = URLEncoder.encode("download.csv", "UTF-8");
builder.header("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);
return builder.body(content.getBytes());
}
三、不适用的情况:直接适用HttpServletResponse进行内容返回的接口。需要将注释的部分打开才能跨域
@RequestMapping("/get/csv2")
public void getCSV2(HttpServletResponse response) {
String resultString="first,second,third";
byte[] bytes = resultString.getBytes();
response.reset();// 清空输出流
response.setContentType("application/x-download");
response.setCharacterEncoding("UTF-8");
response.addHeader("Content-Disposition", "attachment;filename=" + "test" + ".csv");
/* response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE");
response.addHeader("Access-Control-Max-Age", "9600");
response.addHeader("Access-Control-Allow-Headers", "x-requested-with");*/
try {
OutputStream os = response.getOutputStream();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
response.setHeader("Content-Length", String.valueOf(bais.available()));
byte[] b = new byte[1024];
while ((bais.read(b)) > 0) {
os.write(b);
}
bais.close();
os.flush();
os.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
|