Java工程師修煉之道--Spring對跨域請求的支持

跨域請求的支持-Spring CORS
    CORS(Cross-Origin Resource Sharing) 用於解決瀏覽器跨域請求問題,簡單的GET請求可以通過jsonp解決。
    對於稍微複雜的請求則需要後端支持CORS,Spring4.2之後提供了@CrossOrigin註解來提供支持。
  

    //在Controller方法上配置
    @CrossOrigin(origins={"http://localhost:8088"})
    @RequestMapping(value = "/corsTest", method = RequestMethod.GET)
    public String greetings() {
        return "cors test";
    }
    
    //在controller上配置,那麼此controller中所有的method都支持CORS.
    @CrossOrigin(origins = {"http://localhost:8088"})
    @Controller
    @RequestMapping("/api/")
    public class TestController() {
        @RequestMapping(value = "/corsTest", method = RequestMethod.GET)
        public String greetings() {
            return "cors test";
        }
    }
    
    //Java Config全局配置
    @Configuration
    @EnableWebMvc
    public class SpringWebConfig extends WebMvcConfigerAdapter {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            //對所有URL配置
            //registry.addMapping("/**");
            
            //針對某些URL配置
            registry.addMapping("/api/**").allowedOrigins("http://localhost:8088")
                                          .allowedMethods("PUT", "DELETE")
                                          .allowedHeaders("header1", "header2")
                                          .exposedHeaders("header1", "header2)
                                          .allowedCredentials(false).maxAge(3600);
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章