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

SpringMVC从Control中响应json数据

时间:2015-12-31 12:35:04      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:

在页面上异步获取Controller中响应的json数据。

<%@ 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>User List</title>

<script type="text/javascript" src="${pageContext.request.contextPath}/resource/script/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("#button_getUser").click(function(){
            //异步请求json数据
            $.ajax({
                type:"POST",
                url:"${pageContext.request.contextPath}/user/getUserList",
                success:function(data){
                    //迭代返回的json数据
                    $.each(data,function(i,user){
                        $("#results").append(user.userName+"---"+user.password+"<br>");
                    });
                },
                error:function(e) {
                    alert("出错:"+e);
                }
            });
        });
    });
</script>

</head>
<body>
    <input type="button" id="button_getUser" value="获取用户列表"><br>
    用户信息:<br>
    <div id="results">
    
    </div>
</body>
</html>

Controller中的代码:

@RequestMapping("/getUserList")
    public String getUserList(HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        
        List<User> userList = getUsers();
        Gson gson = new Gson();
        String json = gson.toJson(userList);
        System.out.println("json---"+json);
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write(json);
            out.flush();
        }catch(Exception e) {
            e.printStackTrace();
        }finally {
            if(out != null) {
                out.close();
            }
        }
        
        return "/user/userList";
    }
    
    private List<User> getUsers() {
        List<User> users = new ArrayList<User>();
        
        User user1 = new User();
        user1.setUserName("李坏");
        user1.setPassword("LiHuai");
        
        User user2 = new User();
        user2.setUserName("阿飞");
        user2.setPassword("aFei");
        
        User user3 = new User();
        user3.setUserName("陆小凤");
        user3.setPassword("LuXiaoFeng");
        
        users.add(user1);
        users.add(user2);
        users.add(user3);
        
        return users;
    }

或者使用@ResponseBody,需要用到jackson相关的包。

SpringMVC从Control中响应json数据

标签:

原文地址:http://www.cnblogs.com/zhujiabin/p/5090988.html

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