[Spring MVC] - JSON
Spring MVC中使用JSON,先必需引用两个包:jackson-core-asl-1.9.13.jar、jackson-mapper-asl-1.9.13.jar
因为需要使用到jquery测试,如果在项目中的web.xml配置Spring MVC是“/”,比如:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
意思匹配所有的路径使用Spring MVC做解释的话,那么需要在Spring MVC的配置文件中加入:
<mvc:resources location="/js/" mapping="/js/**" />
用于过滤对指定路径不使用Spring MVC解释器。
先看这个model entity:
package com.my.controller.bean;
import org.hibernate.validator.constraints.NotEmpty;
public class Account {
@NotEmpty(message="{valid.required}")
private String userName;
@NotEmpty(message="{valid.required}")
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
这是一个简单的model,使用了annotation做数据验证。
Controller:
package com.my.controller; import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map; import javax.validation.Valid; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView; import com.my.controller.bean.Account; @Controller
@RequestMapping(value="json")
public class TestJsonController { /**
* 静态accounts
*/
private List<Account> accounts = new ArrayList<Account>();
{
Account acc1 = new Account();
Account acc2 = new Account(); acc1.setUserName("Robin");
acc1.setPassword("password"); acc2.setUserName("Lucy");
acc2.setPassword("123456"); accounts.add(acc1);
accounts.add(acc2);
} /**
* 默认地址
* @return
*/
@RequestMapping(method=RequestMethod.GET)
public ModelAndView index() {
ModelAndView view = new ModelAndView("TestJson/index");
view.addObject("accounts", accounts);
return view;
} /**
* 新增account
* @param account
* @param model
* @return
*/
@RequestMapping(value="add", method=RequestMethod.POST)
@ResponseBody
public Map<String, Object> add(@RequestBody @Valid Account account, BindingResult bindingResult) {
Map<String, Object> result = new HashMap<String, Object>(); if(bindingResult.hasErrors()) {
List<FieldError> errs = bindingResult.getFieldErrors();
Map<String, String> mapErrors = new LinkedHashMap<String, String>();
for(FieldError err : errs) {
mapErrors.put(err.getField(), err.getDefaultMessage());
}
result.put("success", false);
result.put("errors", mapErrors);
return result;
} accounts.add(account);
result.put("success", true);
result.put("data", accounts);
return result;
} /**
* 取得所有accounts
* @return
*/
@RequestMapping(value="accounts", method=RequestMethod.GET)
@ResponseBody
public List<Account> findAccounts() {
return accounts;
} }
1、初始了一个static的accounts
2、默认index中有一个view
3、add(...) 方法:
- @ResponseBody这个annotation,意思是直接输出
- 在参数中@RequestBody @Valid这两个annotation是json提交时的需要的,@RequestBody是必需的,@Valid是数据验证必需的
- BindingResult,必需要紧跟实体model之后,否则取不到验证结果
- 本例使用了一个Map做数据返回,Spring MVC会直接对这个Map转换成JSON结果字符串
- 如果验证失败,使用一个map加入错误信息返回
4、findAccounts()方法可以直接返回json。注意@ResponseBody
View:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib prefix="st" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!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">
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.json.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.3.js"></script>
<title>Test Json</title>
<script type="text/javascript"> $(document).ready(function() {
getData();
}); //-------------------------------------------------
// 取得JSON数据
//-------------------------------------------------
function getData() {
var url = "${pageContext.request.contextPath}/json/accounts";
$.get(url).success(function(data, status, xhr) {
setData(data);
});
} //-------------------------------------------------
// 设置JSON数据
//-------------------------------------------------
function setData(data) {
var div = $("#divJson");
div.html("");
$(data).each(function(index, row) {
div.append("User_" + index + ":" + row.userName + "<br/>");
});
} //-------------------------------------------------
// Add按钮事件
//-------------------------------------------------
function addClick() {
var url = "${pageContext.request.contextPath}/json/add";
var data = {
userName: $("#userName").val(),
password: "pass"
};
// POST JSON数据到服务器
$.ajax({
url: url,
dataType: "json",
contentType: "application/json",
type: "POST",
data: JSON.stringify(data),
success: function (data) {
if(data.success) {
setData(data.data);
}
else {
var text = "";
$(data.errors).each(function(index, row) {
text += "<font color='red'>" + row.userName + "</font><br/>";
});
$("#divJson").html(text);
}
},
error: function () {
}
});
}
</script>
</head>
<body>
<b>HTML:</b><hr/>
<c:set scope="page" var="index" value="0"></c:set>
<c:forEach items="${accounts}" var="item">
User_<c:set scope="page" value="${index+1}" var="index"></c:set>${index}:
<c:out value="${item.userName}"></c:out><br/>
</c:forEach>
<hr/>
<b>Json:</b><hr/>
<div id="divJson"></div>
<hr/>
User name:<input type="text" id="userName" name="userName" value="" />
<input type="button" id="btnAdd" name="btnAdd" value="Call Ajax add account" onclick="addClick()" />
</body>
</html>
这里使用正常输出和json输出两种方式。
运行结果:

不输入user name时:

正确输入时:

[Spring MVC] - JSON的更多相关文章
- spring mvc json 返回乱码问题解决(vestion:3.x.x)
本文是转载文章,感觉比较好,如有侵权,请联系本人,我将及时删除. 原文网址:<spring mvc json 返回乱码问题解决(vestion:3.x.x)> 工程中用springmvc返 ...
- spring mvc: json练习
spring mvc: json练习 本例需要用到的json包: 如下: jackson-databind jackson-core jackson-annotations <!-- https ...
- Spring MVC JSON自己定义类型转换(续)
前面提到了两种转换类型的方法(Spring MVC JSON自己定义类型转换),这里针对Json转换提供一种更简便的方法. 通过配置全局的日期转换来避免使用麻烦的注解. 首先用到了一个简单的日期工具类 ...
- Spring MVC JSON 实现JsonSerializer Date类型转换
转载至:http://blog.csdn.net/lantianzhange/article/details/40920933 在Spring MVC中存在两大类的类型转换,一类是Json,一个是Sp ...
- Spring mvc Json 的正确返回姿势
我们经常都需要封装统一JSON格式 例如以下形式 { “data”:“输出的数据”, “code”:“响应代码”, “msg”:“响应信息” } /** * Created by linli on 2 ...
- Spring MVC JSON自己定义类型转换
版权声明:版权归博主全部.转载请带上本文链接.联系方式:abel533@gmail.com https://blog.csdn.net/isea533/article/details/28625071 ...
- spring mvc json返回防止乱码
乱码问题 乱码一直是编程的常见问题,spring mvc 返回json数据时可能导致乱码,需要在controller中添加如下代码: @RequestMapping("/test" ...
- Spring MVC json配置
接口类的Controller,一般返回的是json数据,而Spring MVC中默认返回的string,而jsp页面的话,会按配置中自己行匹配转义字符串为对应的jsp文件. @Controller @ ...
- spring Mvc json返回json的日期格式问题
(一)输出json数据 springmvc中使用jackson-mapper-asl即可进行json输出,在配置上有几点: 1.使用mvc:annotation-driven 2.在依赖管理中添加ja ...
随机推荐
- std::vector<bool>中的坑
http://www.cplusplus.com/reference/vector/vector/?kw=vector C++中,vector<bool>为了达到节省内存的目的,专门做了特 ...
- SQL列最大重复项
SELECT 1 AS co1, 'a' AS co2 INTO #a UNION SELECT 2, 'a' UNION SELECT 11,'a' UNION SELECT 12, 'a' UNI ...
- 子级与父级的margin合并的问题
子级加上了margin以后,发现其父级也移动了相应的margin值.外边距合并.换成padding;在父级上加overflow:hidden;
- vb小程序浅析
系统 : Windows xp 程序 : BJCM10B 程序下载地址 :http://pan.baidu.com/s/1dFyXe29 要求 : 编写注册机 使用工具 : OD 可在看雪论坛中查找关 ...
- 安装Python2.7环境
1.下载并根据提示安装python_2.7.10_x64 2.将安装目录配置到环境变量path中 3.在命令后台中输入Python,出现下图中信息表示安装成功
- [C++] 自己实现快速memcpy
仅在Win32上使用,Win64上不允许内嵌汇编= = __declspec(naked) void* __stdcall __memcpy ( __in void* Dest, // ebp+0x0 ...
- MVC 从后台页面 取前台页面传递过来的值的几种取法
MVC 从后台页面 取前台页面传递过来的值的几种取法 <1>前台页面 Index视图 注意:用户名表单的name值为txtName 密码表单的name值为txtPassword & ...
- redis 原子增一的妙用
有这样一个需求,插入数据库之前需要了解数据库ID号,考虑到不同的主机怎么去协同这个ID呢 同时要保证每个主机分到不同的ID号,这个比较麻烦,如果独立开一个服务来一个C/S操作比较麻烦,幸好REDIS提 ...
- 托管到github上的网页图片在百度浏览器中显示不全
这几天做了个较完整的网页放到github上,上传后看网页效果. 在Firefox浏览器中,显示正常. 在百度浏览器中,空了一大块位置(图片位置),偏偏只空了这一块,其它地方的图片都好好的. 点击f12 ...
- day27_反射
1.反射-概述(掌握) 反射就是在程序运行过程中,通过.class文件动态的获取类的信息(属性,构造,方法),并调用 注意:JAVA不是动态语言,因为动态语言强调在程序运行过程中不仅能获取并调用类里面 ...