Last active
April 29, 2019 10:54
-
-
Save logicjwell/1d03056186cf4ba0dc3f492c597b6682 to your computer and use it in GitHub Desktop.
[springboot中mvc常用配置] #springboot #spring-mvc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Configuration | |
public class WebMvcConfiguration extends WebMvcConfigurerAdapter { | |
/** | |
* 跨域配置 | |
*/ | |
@Override | |
public void addCorsMappings(CorsRegistry registry) { | |
registry.addMapping("/**") | |
.allowedHeaders("*") | |
.exposedHeaders("user,x-auth-token") //在请求头里指定需要的属性 | |
.allowedOrigins("*") | |
.allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS") | |
.allowCredentials(false).maxAge(3600); | |
} | |
/** | |
* 另一种跨域配置 | |
*/ | |
@SuppressWarnings("unchecked") | |
@Bean | |
public FilterRegistrationBean corsFilter() { | |
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); | |
CorsConfiguration corsConfiguration = new CorsConfiguration(); | |
corsConfiguration.setAllowCredentials(true); | |
corsConfiguration.setAllowedOrigins(Arrays.asList(CorsConfiguration.ALL)); | |
corsConfiguration.setAllowedHeaders(Arrays.asList(CorsConfiguration.ALL)); | |
corsConfiguration.setAllowedMethods(Arrays.asList(CorsConfiguration.ALL)); | |
source.registerCorsConfiguration("/**", corsConfiguration); | |
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); | |
bean.setOrder(Ordered.HIGHEST_PRECEDENCE); | |
return bean; | |
} | |
/** | |
* 注册自定义的请求拦截器 | |
*/ | |
@Override | |
public void addInterceptors(InterceptorRegistry registry) { | |
} | |
/** | |
* 响应结果的内容编码 | |
*/ | |
@Bean | |
public HttpMessageConverter<String> responseBodyConverter() { | |
StringHttpMessageConverter converter = new StringHttpMessageConverter( | |
Charset.forName("UTF-8")); | |
return converter; | |
} | |
@Override | |
public void configureMessageConverters( | |
List<HttpMessageConverter<?>> converters) { | |
super.configureMessageConverters(converters); | |
converters.add(responseBodyConverter()); | |
} | |
@Override | |
public void configureContentNegotiation( | |
ContentNegotiationConfigurer configurer) { | |
configurer.favorPathExtension(false); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment