springboot中ajax参数无法传入的问题

在Springboot中使用ajax传递数据出现了异常
org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing

最后代码如下 可解决问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!--登陆页面 要求前端数据用ajax传递到后端-->
<table>
<tr>
<td>
用户名<input type="text" id="username" name="username">
</td>
</tr>
<tr>
<td>
密码<input type="password" id="password" name="password">
</td>
</tr>
<tr>
<!--a标签中如果不设置href属性则无法进行跳转,如href=""表示刷新当前页面-->
<!--javascript:void(0)指定要计算一个表达式但是不返回值-->
<td> <a href="javascript:void(0)" id="dr">登陆</a></td>
</tr>
</table>

ajax如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<script type="text/javascript">
$(function(){
$('#dr').click(function () {
//console.log("ssss"); 观察是否进入改方法
var data= {
"username" : $("#username").val(),
"password" : $("#password").val()
};
$.ajax({
type: "post",
url: "/login",
contentType: "application/json;charset=utf-8",
dataType: 'json',
timeout: 1000,
data: JSON.stringify(data),
success:
function (result) {
<!--成功接收到json数据 则定向到success.html网页-->
window.location.href="../success.html";
},
error:
function () {
window.location.href="../fail.html";
}
});
})
});
</script>

后端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@RestController
public class Login {
@Autowired
private RoleService roleService;

@RequestMapping(value = "/login",produces = MediaType.APPLICATION_JSON_VALUE)
public JSONObject login(@RequestBody(required = false) Role role, ) {
JSONObject jsonObject=new JSONObject();
//任意json数据
jsonObject.put("data","ss");
Integer i = roleService.login(role.getUsername(), role.getPassword());
if (i==1){
System.out.println("登陆成功");
//如果登陆成功返回一个任意json数据,ajax接收到之后会执行success方法
return jsonObject;
}else {
System.out.println("登陆失败");
//登陆失败则返回null,ajax没有接收到json数据则会执行error方法
return null;
}
}
}
赏个🍗吧
0%