ajax请求如果是json的方式,服务器无法获取参数
按老师的代码如果请求参数是使用"参数名=数据"的方式进行提交数据,spring mvc可以获取到数据。
但是当ajax请求使用json进行数据提交时,spring mvc的post put delete请求都无法获取到参数,请问是什么问题呢?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-3.4.1.min.js"></script>
<script>
$(function () {
$("#get").click(function () {
$.ajax({
type : "get",
url : "/rest/get",
contentType: "application/json;charset=utf-8",
data : {"name" : "获取"},
success : function(json) {
$("#context").text(json);
}
});
});
$("#post").click(function () {
$.ajax({
type : "post",
url : "/rest/post",
contentType: "application/json;charset=utf-8",
data : {"name" : "测试"},
success : function(json) {
$("#context").text(json);
}
});
});
$("#put").click(function () {
$.ajax({
type : "put",
url : "/rest/put",
contentType: "application/json;charset=utf-8",
data : {"name" : "修改"},
success : function(json) {
$("#context").text(json);
}
});
});
$("#delete").click(function () {
$.ajax({
type : "delete",
url : "/rest/delete",
contentType: "application/json;charset=utf-8",
data : {"name" : "删除"},
success : function(json) {
$("#context").text(json);
}
});
});
});
</script>
</head>
<body>
<input id="get" type="button" value="get请求"/>
<input id="post" type="button" value="post请求"/>
<input id="put" type="button" value="put请求"/>
<input id="delete" type="button" value="delete请求"/>
<br/>
<div id="context"/>
</body>
</html>package com.test.controller;
import com.test.entity.Entity;
import org.springframework.web.bind.annotation.*;
@org.springframework.web.bind.annotation.RestController
@RequestMapping("/rest")
public class RestController {
@GetMapping("test1")
public Entity test1(int id, String name) {
Entity entity = new Entity(id, name);
return entity;
}
@GetMapping("test2")
public String test2(int id, String name) {
return "{\"id\":" + id + ",\"name\":\"" + name + "\"}";
}
@GetMapping("get")
public String getTest(String name) {
return "{\"name\":\"" + name + "\"}";
}
@PostMapping("post")
public String postTest(String name) {
return "{\"name\":\"" + name + "\"}";
}
@PutMapping("put")
public String putTest(String name) {
return "{\"name\":\"" + name + "\"}";
}
@DeleteMapping("delete")
public String deleteTest(String name) {
return "{\"name\":\"" + name + "\"}";
}
}web.xml的FormContentFilter过滤器已配置
37
收起
正在回答
2回答
同学你好,这里使用json提交数据 ,后台应该使用get才能接收到数据。这里理解错误,将put请求,delete请求转换为get请求是指在form表达中,增加<input type="hidden" name="_method" value="get">这种方式,在web.xml中,经过HiddenHttpMethodFilter过滤器,会将其他请求转换为get请求。过滤器配置如:

祝:学习愉快~
4. SSM到Spring Boot入门与综合实战
- 参与学习 人
- 提交作业 323 份
- 解答问题 8263 个
本阶段将带你学习主流框架SSM,以及SpringBoot ,打通成为Java工程师的最后一公里!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星