跨域:指的是瀏覽器不能執⾏其他⽹站的腳本。它是由瀏覽器的同源策略造成的,是瀏覽器對javascript施加的安全限制。
例如:a頁⾯想取得b頁⾯資源,如果a、b頁⾯的協定、網域名稱、端⼝、⼦網域不同,所進⾏的存取⾏動都是跨網域的,⽽瀏覽器
為了安全問題⼀般都限制了跨域訪問,也就是不允許跨域請求資源。注意:跨域限制訪問,其實是瀏覽器的限制。理解這⼀點
很重要
同源策略:是指協議,域名,端⼝都要相同,其中有⼀個不同都會產⽣跨域;
直接在Controller方法或類別上增加@CrossOrigin註解,SpringMVC使用@CrossOrigin使用場景要求jdk1.8 Spring4.2
@GetMapping("/hello") @CrossOrigin public String hello() { return "hello:" + simpleDateFormat.format(new Date()); }
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration public class ConfigConfiguration { @Bean public CorsFilter CorsFilter() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOriginPattern("*"); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); corsConfiguration.setAllowCredentials(true); UrlBasedCorsConfigurationSource ub = new UrlBasedCorsConfigurationSource(); ub.registerCorsConfiguration("/**", corsConfiguration); return new CorsFilter(ub); } }
@Component public class CustomFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse) servletResponse; // 设置允许Cookie res.addHeader("Access-Control-Allow-Credentials", "true"); // 允许http://www.xxx.com域(自行设置,这里只做示例)发起跨域请求 res.addHeader("Access-Control-Allow-Origin", "*"); // 设置允许跨域请求的方法 res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); // 允许跨域请求包含content-type res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN"); if (((HttpServletRequest) servletRequest).getMethod().equals("OPTIONS")) { servletResponse.getWriter().println("ok"); return; } filterChain.doFilter(servletRequest, servletResponse); } }
import org.springframework.stereotype.Component; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Component public class MyWebMvcConfigurer implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // 匹配所有的路径 .allowCredentials(true) // 设置允许凭证 .allowedHeaders("*") // 设置请求头 .allowedMethods("GET", "POST", "PUT", "DELETE") // 设置允许的方式 .allowedOriginPatterns("*"); } }
以上是springboot解決跨域的方式有哪些的詳細內容。更多資訊請關注PHP中文網其他相關文章!