• Spring MVC学习12跨域


    域:协议 + 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>
  • 相关阅读:
    丰富eclipse注解的内容
    ThreadLocal总结
    算法+结构?设计模式?
    面试需要准备内容
    HIbernate-0.8版本源码翻看
    2019第一篇博文
    随笔
    Expert one on one 读书笔记之容器
    Expert one on one development without ejb读书笔记
    Mysql索引部分学习关于多列索引的部分
  • 原文地址:https://www.cnblogs.com/asenyang/p/15468863.html
Copyright © 2020-2023  润新知