springmvc json结合

获取json数据     名字一样就获取了

user
     @RequestMapping("/addUser")
public String addUser(User user,HttpServletRequest request){
request.setAttribute("userName", user.getUserName());
request.setAttribute("age", user.getAge()); return "/userManager";
}

传递json数据

     public void addUserJson(User user,HttpServletRequest request,HttpServletResponse response){
//{"username":"userName","age","age"}
String result = "{\"userName\":\" "+ user.getUserName() +" \",\"age\":\" "+ user.getAge()+" \"}";
PrintWriter out = null;
response.setContentType("application/json"); try {
out = response.getWriter();
out.write(result);
} catch (IOException e) {
e.printStackTrace();
} }

jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="/springMVC6/js/jquery-1.7.1.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
$(document).ready(function(){
$("#add").click(function(){
var userName = $("#userName").attr("value");
var age =$("#age").attr("value"); var user = {userName:userName,age:age}; $.ajax({
url:"/springMVC6/user/data/addUserJson",
type:"post",
data:user,
success:function(a){   //传递过来数据
alert("userName--->" + a.userName + "age--->" + a.age ); }
}); });
});
</script>
</head>
<body>
<h>json添加用户</h>
姓名:<input type="text" id="userName" name="userName">
年龄:<input type="text" id="age" name="age">
<input type="button" id="add" value="添加"> </body>
</html>
上一篇:Linux系统下安装jdk及环境配置(两种方法)


下一篇:查找linux系统下的端口被占用进程的两种方法 【转】