Using annotations to solve cross-domain problems of AJAX requests
1. Write a Configuration that supports cross-domain requests
-The first way-Corsconfig.java
Importorg.springframework.context.annotation.Configuration;ImportOrg.springframework.web.servlet.config.annotation.CorsRegistry;ImportOrg.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;/*** Handling Ajax requests cross-domain issues *@authorLevin * @time 2017-07-13*/@Configuration Public classCorsconfigextendsWebmvcconfigureradapter {Static FinalString origins[] =NewString[] {"GET", "POST", "PUT", "DELETE" }; @Override Public voidaddcorsmappings (Corsregistry registry) {registry.addmapping ("/**"). Allowedorigins ("*"). Allowcredentials (true). Allowedmethods (Origins). MaxAge (3600); }}
2.HTTP Request Interface
-Hellocontroller.java
@RestController Public class Hellocontroller { @Autowired helloservice helloservice; = "/test", produces = mediatype.application_json_utf8_value) public String query () { return "Hello"; }}
-Second way (recommended)
PS: First there is a problem, when the server throws 500, there are still cross-domain issues
@SpringBootApplication @componentscan@enablediscoveryclient Public classmanagementapplication { Public Static voidMain (string[] args) {Springapplication.run (managementapplication.class, args); } Privatecorsconfiguration Buildconfig () {corsconfiguration corsconfiguration=Newcorsconfiguration (); Corsconfiguration.addallowedorigin ("*"); Corsconfiguration.addallowedheader ("*"); Corsconfiguration.addallowedmethod ("*"); Corsconfiguration.addexposedheader (Httpheaderconstant.x_total_count); returncorsconfiguration; } /*** Cross-domain filter * *@return */@Bean PublicCorsfilter Corsfilter () {Urlbasedcorsconfigurationsource source=NewUrlbasedcorsconfigurationsource (); Source.registercorsconfiguration ("/**", Buildconfig ());//4 return Newcorsfilter (source); }}-Index.html
<! DOCTYPE html>$ (document). Ready ( function () { $ ("button"). Click (function () { $.ajax ({url:"http://localhost:8080/test", Success:function (Result) { $ ("#p1"). HTML (result);} }); } ); </script>Springboot support for Ajax cross-domain requests