Server配置
配置文件:org.springframework.boot.autoconfigure.web.ServerProperties
server:
# 应用端口
port: 8081
servlet:
# 应用的上下文路径
context-path: /springboot1
Resource配置
配置文件:org.springframework.boot.autoconfigure.web.ResourceProperties
默认配置目录:classpath:/META-INF/resources/
,classpath:/resources/
,classpath:/static/
,classpath:/public/
public class ResourceProperties {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/", "classpath:/resources/",
"classpath:/static/", "classpath:/public/" };
//...
}
}
如在classpath:/static/目录下面放置了 test1.png 通过:http://127.0.0.1:8080/test1.png
即可访问。有时候需要将项止clean。
欢迎页
在classpath:/static/目录下添加index.html即可访问:http://localhost:8080/
拦截器
拦截器的说明: SpringMVC-拦截器
@Configuration
public class MVCConfig implements WebMvcConfigurer {
@Autowired
private GlobalInterceptor globalInterceptor;
/**
* 拦截器
*
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(globalInterceptor).addPathPatterns("/*");
}
}
CORS支持
从4.2版本开始,Spring MVC对CORS提供开箱即用的支持。不用添加任何特殊配置。
1、只需要在Spring Boot应用的controller方法上注解@CrossOrigin,并添加CORS配置。
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CrossOrigin {
String[] DEFAULT_ORIGINS = { "*" };
String[] DEFAULT_ALLOWED_HEADERS = { "*" };
boolean DEFAULT_ALLOW_CREDENTIALS = true;
long DEFAULT_MAX_AGE = 1800;
/**
* 同origins属性一样
*/
@AliasFor("origins")
String[] value() default {};
/**
* 所有支持域的集合,例如"http://domain1.com"。
* <p>这些值都显示在请求头中的Access-Control-Allow-Origin
* "*"代表所有域的请求都支持
* <p>如果没有定义,所有请求的域都支持
* @see #value
*/
@AliasFor("value")
String[] origins() default {};
/**
* 允许请求头重的header,默认都支持
*/
String[] allowedHeaders() default {};
/**
* 响应头中允许访问的header,默认为空
*/
String[] exposedHeaders() default {};
/**
* 请求支持的方法,例如"{RequestMethod.GET, RequestMethod.POST}"}。
* 默认支持RequestMapping中设置的方法
*/
RequestMethod[] methods() default {};
/**
* 是否允许cookie随请求发送,使用时必须指定具体的域
*/
String allowCredentials() default "";
/**
* 预请求的结果的有效期,默认30分钟
*/
long maxAge() default -1;
}
2、通过注册一个自定义addCorsMappings(CorsRegistry)方法的WebMvcConfigurer bean可以指定全局CORS配置:
@Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**");
}
};
}
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://domain2.com")
.allowedMethods("PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(false).maxAge(3600);
}