域:协议 + ip(域名) + 端口

建立Controller:

 1 package com.yas.controller;
 2 
 3 import org.springframework.web.bind.annotation.CrossOrigin;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 import org.springframework.web.bind.annotation.RestController;
 6 
 7 import javax.servlet.http.HttpSession;
 8 
 9 @RequestMapping("/origin")
10 @RestController
11 @CrossOrigin("http://localhost:8080")//设置前端server的地址
12 public class SysUserController {
13 
14     @RequestMapping("/test1")
15     public String test1(HttpSession session) {
16         session.setAttribute("name", "zhangsan");
17         System.out.println("存入session");
18         return "ok";
19     }
20 
21     @RequestMapping("/test2")
22     public String test2(HttpSession session) {
23         String name = (String) session.getAttribute("name");
24         System.out.println("从session中取出数据:" + name);
25         return "ok";
26     }
27 }

 

测试页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="https://code.jquery.com/jquery-2.1.0.min.js"></script>
    <script>
      function getCross(){
        $.ajax({
          url:"http://localhost:8080/origin/test1",
          type:"post",
          xhrFields:{
            withCredentials:true
          },
          success:function (d){
            console.log(d);
          }
        });
      }
      function getCross2(){
        $.ajax({
          url:"http://localhost:8080/origin/test2",
          type:"post",
          xhrFields:{
            withCredentials:true
          },
          success:function (d){
            console.log(d);
          }
        });
      }
    </script>
</head>
<body>
  <input type="button" value="跨域请求" onclick="getCross()">
  <input type="button" value="跨域请求2" onclick="getCross2()">
</body>
</html>

 

posted on 2021-10-27 08:26  Sempron2800+  阅读(27)  评论(0编辑  收藏  举报