本文转自网易博客,作者:月上西楼,时间:2015-4-2
我们做一个如下页面的功能,输入用户名、密码然后显示用户名与密码到页面,使用AJAX和JSON方式.
首先,新建json.jsp文件,内容如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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>JSON测试</title> <script type="text/javascript" src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#loginBtn").click(function(){ var username = $("#username").val(); var password = $("#password").val(); var userJosn = {"username":username,"password":password}; $.ajax({ url:"/testAnnotationMVC2/test/json.jspx", type:"post", data:userJosn, success: function(data){ $("#msg").html("name="+data.name+" ,pwd="+data.pwd); } }); }); }); //由此我们可以看出,jquary中的ajax也是json格式的 </script> </head> <body> <h3>用户登录</h3> <form name="userForm" action=""> 用户名:<input type="text" id="username" name="username"> 密码:<input type="text" id="password" name="password"> <input type="button" value="登录" id="loginBtn" /> </form> <br/> 结果:<span id="msg"></span> </body> </html> |
然后新建在controller里首先写一个跳转到json.jsp页面的方法toJosn:
@RequestMapping("/toJson") public String toJosn() { return "json"; } |
接着写json处理方法:
@RequestMapping("/json") public void showInfoJson(User user, HttpServletRequest request, HttpServletResponse response) { String result = "{\"name\":\""+user.getUsername()+"\",\"pwd\":\""+user.getPassword()+"\"}";//user //接到前台传到的数据,并拼接成新的json对象 response.setContentType("application/json");//设置response的传输格式为json System.out.println(result); try { PrintWriter out = response.getWriter(); out.write(result);//给页面上传输json对象 } catch (IOException e) { e.printStackTrace(); } } |
User:
public class User { private long id; private String username; private String password; //get、set省略... } |
这样就实现了简单的JSON数据传输。
参考文献:
[1]月上西楼. SpringMVC(5)传递JSON数据实例.[EB/OL]. http://blog.163.com/zhangmihuo_2007/blog/static/27011075201462094716/