js传递数据给spring后端代码演示

html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jstest</title>
<script src="jstest.js"></script>
</head>
<body>
<button onclick="postRequest()" th:action="sumbit2">test</button>
</body>
</html>

js代码

function postRequest(){

    var httpRequest = new XMLHttpRequest();	//第一步:创建需要的对象
    httpRequest.open('POST', "/submit2", true);	//第二步:打开连接,该网址必须与html的动作网址相同也就是th:action里面的网址。后端控制器也将监听该网址
    /***发送json格式文件必须设置请求头 ;如下 - */
    httpRequest.setRequestHeader("Content-type","application/json; charset=utf-8");	// 设置请求头,注:post方式必须设置请求头(在建立连接后设置请求头)
    var obj = {
        sendName:"js",
        sendInfo:"hello",
        receiver:"java"
    }
    httpRequest.send(JSON.stringify(obj));//发送请求 将json写入send中

}

Java代码

package com.example.studentsbusnissmanagesystem.controller;

import com.example.studentsbusnissmanagesystem.DAO.jstest;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

//js想要传递json数据就要使用xhr函数将要传递的信息字符串化,然后设置请求头。请求头的网址必须与html页面的创建网址或者是派生网址相同
//
@Controller
public class JsTestController {

    @PostMapping("/jstest")

    public String mapping(){
        return "jstest";
    }


    @PostMapping("submit2")
    public String postRequest(@RequestBody jstest jstest){
        System.out.println(jstest.toString());
        return "jstest";
    }

}

数据类

import lombok.Data;

@Data
public class jstest {
    String sendName,sendInfo,receiver;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值