Ajax+springmvc realizes cross-domain request

Ajax cross-domain request (after spring framework version 4.2)

1. Error message


jquery-3.1.1.min.js:4 XMLHttpRequest cannot load http://127.0.0.1:8080/user/login.action. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

2. Solutions


1. Method 1: @CrossOrigin annotation
  • That is, in the Controller controller, add the @CrossOrigin annotation above the Controller annotation.
@CrossOrigin(origins = {"*"}, maxAge = 3600)
public classUserController{}
  • Official website: www.fhadmin.org You can also add the @CrossOrigin annotation to each method in the Controller controller.
@CrossOrigin(origins = {"*"}, maxAge = 3600)
public String login(String username, String password)throws Exception {}
  • If there is still a cross-domain problem after adding, you need to configure the request method (method) in the mapping path
@RequestMapping(value = "user", method = {RequestMethod.POST})
@CrossOrigin(origins = {"*"}, maxAge = 3600)
public class UserController {}
2. Method 2: CORS global configuration
  • XML-based configuration, configured in springmvc.xml
<!-- 跨域请求 -->
<mvc:cors>
    <mvc:mappingpath="/user/*"/>
</mvc:cors>
  • Official website: www.fhadmin.org for detailed configuration
<mvc:cors>
    <mvc:mappingpath="/api/**"allowed-origins="http://domain1.com, http://domain2.com"allowed-methods="GET, PUT"allowed-headers="header1, header2, header3"exposed-headers="header1, header2"allow-credentials="false"max-age="123" />
    <mvc:mappingpath="/resources/**"allowed-origins="http://domain1.com" />
</mvc:cors>
  • If there is a "wildcard match very comprehensive, but the declaration of the element 'mvc:cors' could not be found." Such an error.
解决办法:
    查看文件上边beans中xsd文件引入的版本是不是不对。

如下所示:
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd

引入的xsd版本为3.0,而mvc:cors是4.2版本的功能。
因此,只需要将xsd版本更新就行。
    http://www.springframework.org/schema/mvc/spring-mvc.xsd
或者设置成4.2以上的。

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326991771&siteId=291194637