配置类
package cn.edu.qfnu.soft.common.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 跨域配置
* @author Louis
* @date Jan 12, 2019
*/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
/**
* @author 吕嘉鸣
* 配置图片服务映射
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/img/**").addResourceLocations("file:D:/photos/");
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 允许跨域访问的路径
.allowedOrigins("*") // 允许跨域访问的源
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE") // 允许请求方法
.maxAge(168000) // 预检间隔时间
.allowedHeaders("*") // 允许头部设置
.allowCredentials(true); // 是否发送cookie
}
}
拼接映射访问路径
@Override
public String 拼接映射访问路径( HttpServletRequest request) {
ChkBillImg chkBillImg = chkBillImgMapper.selectOne(queryWrapper);
String httpUrl = chkBillImg.getUrl().replace("D:\photos\", "").replace("\", "/");
try {
httpUrl = "101.201.148.143"+":"+String.valueOf(request.getServerPort())+ File.separator +"img"+File.separator+httpUrl;
httpUrl = "http://"+httpUrl.replace("\", "/");
chkBillImg.setUrl(httpUrl);
} catch (SocketException e) {
e.printStackTrace();
}
return httpUrl;
}