码迷,mamicode.com
首页 > 编程语言 > 详细

springmvc json结合

时间:2014-07-05 19:04:55      阅读:353      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   java   color   数据   

获取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>

 

springmvc json结合,布布扣,bubuko.com

springmvc json结合

标签:style   blog   http   java   color   数据   

原文地址:http://www.cnblogs.com/friends-wf/p/3822659.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!