# cors

“跨域资源共享”(Cross-origin resource sharing)

// from https://blog.csdn.net/c5113620/article/details/79132968

@Configuration
public class CorsConfiger extends WebMvcConfigurer{
  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
        .allowedOrigins("*")
        .allowCredentials(true)
        .allowedMethods("GET", "POST", "DELETE", "PUT")
        .maxAge(3600);
  }


// 当有其他***时,需要加上(这种情况,上面配置也可不要)
 private CorsConfiguration corsConfig() {
		CorsConfiguration corsConfiguration = new CorsConfiguration();
		/* * 请求常用的三种配置,*代表允许所有,当然你也可以自定义属性(比如header只能带什么,只能是post方式等等) */
		// 允许访问的客户端域名
		corsConfiguration.addAllowedOrigin("*");
		// 允许任何请求头 可选: "x-requested-with,X-Nideshop-Token,X-URL-PATH"
		corsConfiguration.addAllowedHeader("*");
		// 允许任何方法 可选: "POST, GET, OPTIONS, DELETE"
		corsConfiguration.addAllowedMethod("*");
		// 允许请求带有验证信息
		corsConfiguration.setAllowCredentials(true);
		// maxAge(3600)表明在3600秒内,不需要再发送预检验请求,可以缓存该结果
		corsConfiguration.setMaxAge(3600L);
		return corsConfiguration;
	}

	@Bean
	public CorsFilter corsFilter() {
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		// 拦截本域名下的所有请求
		source.registerCorsConfiguration("/**", corsConfig()); // 设置头配置信息
		return new CorsFilter(source);
	}

《跨域资源共享 CORS 详解》

# jsonp

MappingJackson2HttpMessageConverter 功能增强

实现服务端 jsonp 响应
(如果前端请求包含 callback=aaa 参数,则结果用 aaa(...) 包裹返回)

package cn.test.config;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.fasterxml.jackson.core.JsonGenerator;

@Configuration
public class JsonpConfig {
	@Bean
	public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
		return new MappingJackson2HttpMessageConverter() {
			// 做jsonp的支持的标识,在请求参数中加该参数
			private final static String CALLBACK = "callback";

			// 获取callback参数
			private String parseCallbackParam() {
				HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
						.currentRequestAttributes()).getRequest();
				return request.getParameter(CALLBACK);
			}

			@Override
			protected void writePrefix(JsonGenerator generator, Object object) throws IOException {
				String callback = parseCallbackParam();
				if (!StringUtils.isEmpty(callback))
					generator.writeRaw(callback + "(");
			}

			@Override
			protected void writeSuffix(JsonGenerator generator, Object object) throws IOException {
				String callback = parseCallbackParam();
				if (!StringUtils.isEmpty(callback))
					generator.writeRaw(")");
			}
		};
	}
}

# websocket