SpringBoot中如何返回对象,与前端交互,这里我们使用到一个核心注解
@ResponseBody
当方法中使用了 @ResponseBody注解,就代表,方法返回的试一个JSON对象了,而不是网页地址了。SpringBoot默认JackJson.:下面我们开始测试demo:
这里我们不多讲SpringBoot+Mybatis项目的配置:
如果项目搭建有问题,可以参考以下内容:
[SpringBoot+Mhybatis的项目搭建实现一个插入demo](https://blog.csdn.net/weixin_43957143/article/details/97020939)
1.创建一个实体类:User:
public class User {
private String id;
private String username;
private String password;
private String idcard;
private Integer sex;
private String realname;
private Long mobile;
private String rolename;
public User() {
}
public String getRolename() {
return rolename;
}
public void setRolename(String rolename) {
this.rolename = rolename;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getIdcard() {
return idcard;
}
public void setIdcard(String idcard) {
this.idcard = idcard;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname;
}
public Long getMobile() {
return mobile;
}
public void setMobile(Long mobile) {
this.mobile = mobile;
}
public User(String username, String password, String idcard, Integer sex, String realname, Long mobile, String rolename) {
this.username = username;
this.password = password;
this.idcard = idcard;
this.sex = sex;
this.realname = realname;
this.mobile = mobile;
this.rolename = rolename;
}
}
2.写一个Controller:一个用来返回到页面,一个是获得数据
@RequestMapping(value="/index",method=RequestMethod.POST)
@ResponseBody
public User findUser(User user) {
try {
//user= userService.findUserByUser(user);
//方便测试,不和数据库交互,前端拿username属性的值;
user.setUsername("没有眉毛的阿斗");
return user;
} catch(Exception e) {
return null;
}
}
3.前端页面:/registry/query.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>查询用户</title>
<script src="/js/jquery-1.9.1.js"></script>
</head>
<script>
function query() {
$.ajax({
url:"/index",
type:"post",
data:{
id:$("#userId").val(),
},
success:function(data){
console.log(data);
$("#username").val(data.username);
}
})
}
</script>
<body>
<div id="app">
<form action="/index" method="post">
请输入ID:<input type="text" name="id" id="userId"/>
<input type="button" value="查询" onclick="query()" />
您的用户名是:<input type="text" name="username" id="username"/>
</form>
</div>
</body>
</html>
这里我们用是Jquery版。
4.启动项目,浏览器中输入:localhost:8080/query
随便输入,我们发现获得了用户名的值。说明ajax请求成功了。
版权声明:本文为weixin_43957143原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。