First, Web development often encounter cross-domain problems, solutions are: jsonp,iframe,cors, etc.
CORS compared to JSONP
1. JSONP can only implement GET requests, and CORS supports all types of HTTP requests.
2, using CORS, developers can use ordinary XMLHttpRequest to initiate requests and obtain data, compared to JSONP have a better
Error handling.
3, JSONP is mainly supported by the old browser, they often do not support cors, and most modern browsers have supported Cors
Browser support Scenarios
Chrome
Firefox 3.5+
Opera 12+
Safari 4+
Internet Explorer 8+
Second, you can configure global rules in spring MVC, or you can use @crossorigin annotations for fine-grained configuration
Global configuration:
@Configuration public class Customcorsconfiguration { @Bean public webmvcconfigurer corsconfigurer () { return new Webmvcconfigureradapter () { @Override public void Addcorsmappings (Corsregistry registry) { Registry.addmapping ("/api/**"). Allowedorigins ("http://localhost:8080"); } ;
or a
@Configuration public class CustomCorsConfiguration2 extends Webmvcconfigureradapter { @Override public Void Addcorsmappings (Corsregistry registry) { registry.addmapping ("/api/**"). Allowedorigins ("http://localhost:8080");
Define the method:
@RestController @RequestMapping ("/api") public class Apicontroller { @RequestMapping (value = "/get") public Hashmap<string, object> get (@RequestParam String name) { hashmap<string, object> map = new hashmap< String, object> (); Map.put ("title", "Hello World"); Map.put ("name", name); return map;
Test JS:
$.ajax ({ URL: "Http://localhost:8081/api/get", Type: "POST", data: { name: "Test" }, Success:function (data, status, XHR) { console.log (data); alert (data.name); } });
Fine-grained configuration:
@RestController @requestmapping (value = "/api", method = requestmethod.post) public class Apicontroller {@CrossOrigin ( Origins = "http://localhost:8080") @RequestMapping (value = "/get") public hashmap<string, object> get (@ Requestparam String name) {hashmap<string, object> map = new hashmap<string, object> (); Map.put ("title", " Hello World "); Map.put (" name ", name); return map;}}
Springboot--Web application development-cors support