admin 管理员组

文章数量: 887021

SpringMVC

1. ajax跨域请求

跨域请求相当于Tomcat的URL为:
http://localhost:8080/springMVC08_war_exploded/
访问另一个Tomcat的URL为:
http://localhost:8989/springMVC09_war_exploded/的路径

  • Tomcat运行8080的项目,访问8989,访问路径为:http://localhost:8989/springMVC09_war_exploded/origin/test1,

  • 发现不能访问

  • 在ajax调用的方法或其所在类上添加@CrossOrigin注解,

  • @CrossOrigin(“http://localhost:8989”)//设置允许这个域名访问

<input type="button" value="cross_origin" onclick="cross_origin();">
<script>
function cross_origin(){$.ajax({type: "GET",url: "http://localhost:8989/springMVC09_war_exploded/origin/test1",dataType: "text",success: function (code) {alert(code);},error: function (code) {alert("error")}});
}</script>
    @CrossOrigin("http://localhost:8989")//设置允许这个域名访问@RequestMapping("/origin")@RestControllerpublic class OriginController(){@RequestMapping("/test1")public String test1(HttpSession session){System.out.println("test1");session.setAttribute("name","lyx");return "ok";	}@RequestMapping("/test2")public String test2(HttpSession session){System.out.println("test2");String name = (String)session.getAttribute("name");return "ok";	}}

这行代码会自动添加响应头:
Access-Control-Allow-Origin:“http://localhost:8989”
相当于代码:

response.addHeader(‘Access-Control-Allow-Origin:*’);//允许所有来源访问
response.addHeader(‘Access-Control-Allow-Method:POST,GET’);//允许访问的方
  • 添加注释以后,Tomcat运行8080的项目,访问8989,ajax访问路径为:http://localhost:8989/springMVC09_war_exploded/origin/test1,
  • 发现可以访问8989这个域名下的origin/test1,成功运行test1这个方法
  • 但是我们在8080项目中ajax访问路径:http://localhost:8989/springMVC09_war_exploded/origin/test2,
  • test2方法中:String name = (String)session.getAttribute(“name”);不能成功获取到name值,说明并没有携带刚刚test1方法中:session.setAttribute(“name”,“lyx”);
    这个session作用域里的数据

2. 携带对方cookie,使得session可用

  • 携带对方cookie,使得session可用
  • 在访问方,Ajax中添加属性:
 xhrFields:{//跨域携带cookiewithCredentials:true},
  • 具体代码如下
<input type="button" value="cross_origin" onclick="cross_origin();">
<input type="button" value="cross_origin2" onclick="cross_origin2();">
<script>
function cross_origin(){$.ajax({type: "GET",url: "${pageContext.request.contextPath}/origin/test1",dataType: "text",success: function (code) {alert(code);},error: function (code) {alert("error")}});
}
function cross_origin2(){$.ajax({type: "GET",url: "${pageContext.request.contextPath}/origin/test2",xhrFields:{//跨域携带cookiewithCredentials:true},success: function (code) {alert(code);},error: function (code) {alert("error")}});
}</script>

本文标签: SpringMVC