简单回顾了一下SpringMVC和前端JSON数据是怎么交互的

接下来详细说一下过程

前端代码写的很简单  主要是为了试验一下JSON数据的前后台传递

 

前端代码给大家发出来 其实真的很简单 前端接受了一个用户user

把它转化为JSON格式的  然后使用ajax进行前后端传递(页面不需要重新加载)

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/pages/common/head.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="${basePath}/resource/js/jquery-3.2.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#button_submit").click(function(){
var name=$("#username").val();
var pass=$("#password").val();

var user={userName:name,password:pass};

$.ajax({
type:"POST",
url:"${basePath}/addUser.do",
data:user,
success:function(data){
alert("成功");
},
error:function(e){
alert("出错"+e);
}
})
})
})
</script>
</head>
<body>
<form>
<table>
<tr>
<td>账号</td>
<td>
<input type="text" id="username" name="userName">
</td>
</tr>
<tr>
<td>密码</td>
<td>
<input type="text" id="password" name="password" >
</td>
</tr>
<tr>
<td></td>
<td>
<input type="button" id="button_submit" value="提交" />
</td>
</tr>
</table>
</form>
</body>
</html>

 

这里注意SpringMVC接受参数的时候只需要把把要接受的参数写到参数列表中就可以了

也可以直接接受一个实体类  所以我们先建一个实体类User

 

package com.KaiYun.SSHDemo.entity;

public class User {
//用户姓名
private String userName;
//用户密码
private String password;

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;
}

}

然后就是Controller层的代码

 

package com.KaiYun.SSHDemo.controller;

 

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.KaiYun.SSHDemo.entity.User;

 

@Controller
public class TestController {
@RequestMapping("/test.do")
public String test(){
return "/test";
}

@RequestMapping("/addUser.do")
@ResponseBody
public String addUser(User user,ModelMap modelmap){
System.out.println("username is "+user.getUserName());
System.out.println("userPwd id "+user.getPassword());
return null;
}

}

结果就是在前端输入的数据最后在控制台输出 

一个用户姓名一个用户密码

 

基本就是这样了  最近也要开始写代码喽