获取json数据 名字一样就获取了
user
1 @RequestMapping("/addUser") 2 public String addUser(User user,HttpServletRequest request){ 3 request.setAttribute("userName", user.getUserName()); 4 request.setAttribute("age", user.getAge()); 5 6 return "/userManager"; 7 }
传递json数据
1 public void addUserJson(User user,HttpServletRequest request,HttpServletResponse response){ 2 //{"username":"userName","age","age"} 3 String result = "{\"userName\":\" "+ user.getUserName() +" \",\"age\":\" "+ user.getAge()+" \"}"; 4 PrintWriter out = null; 5 response.setContentType("application/json"); 6 7 try { 8 out = response.getWriter(); 9 out.write(result); 10 } catch (IOException e) { 11 e.printStackTrace(); 12 } 13 14 }
jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 4 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 5 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 6 <html> 7 <head> 8 <script type="text/javascript" src="/springMVC6/js/jquery-1.7.1.min.js"></script> 9 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 10 <title>Insert title here</title> 11 <script type="text/javascript"> 12 $(document).ready(function(){ 13 $("#add").click(function(){ 14 var userName = $("#userName").attr("value"); 15 var age =$("#age").attr("value"); 16 17 var user = {userName:userName,age:age}; 18 19 $.ajax({ 20 url:"/springMVC6/user/data/addUserJson", 21 type:"post", 22 data:user, 23 success:function(a){ //传递过来数据 24 alert("userName--->" + a.userName + "age--->" + a.age ); 25 26 } 27 }); 28 29 30 31 }); 32 }); 33 </script> 34 </head> 35 <body> 36 <h>json添加用户</h> 37 姓名:<input type="text" id="userName" name="userName"> 38 年龄:<input type="text" id="age" name="age"> 39 <input type="button" id="add" value="添加"> 40 41 </body> 42 </html>