方法一: 創建一個filter解決跨域,此方法也支持springmvc。
@Component public class SimpleCORSFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With"); chain.doFilter(req, res); } public void init(FilterConfig filterConfig) {} public void destroy() {} }
方法二:基於繼承WebMvcConfigurerAdapter或者實現WebMvcConfigurer接口配置加入Cors的跨域,此方法常用於springboot。
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class CorsConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowCredentials(true) .allowedMethods("GET", "POST", "DELETE", "PUT") .maxAge(3600); } }
import com.common.constant.TokenConstants; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { // 設置允許跨域的路由 registry.addMapping("/**") // 設置允許跨域請求的域名 .allowedOriginPatterns("*") // 是否允許證書(cookies) .allowCredentials(true) // 設置允許的方法 .allowedMethods("*") // 跨域允許時間 .maxAge(3600); } }
方法三:設置特別控制層允許跨域
@CrossOrigin(origins = "http://192.168.1.10:8080", maxAge = 3600) @RequestMapping("/index") @RestController public class IndexController{ }
@CrossOrigin這個注解在controller類中使用,就可以指定該controller中所有方法都能處理來自http:19.168.1.10:8080中的請求。