一:Spring MVC 的controller接收前台的json的数据
获取前台的json的有多种方式,但是常用的有两种方式:
(1)利用Spring提供的@Request方式,但是这中方式有很大的限制。前台ajax的请求(1)必须用post请求(2)data:json对象必须转化成json字符串(3)必须设置contentType: "application/json;charset=UTF-8",否则后台都无法获得json数据。
前台的ajax请求:
$.ajax({
url:"http://127.0.0.1:8080/SSM_maven/getUser",
data:JSON.stringify(data),
type:"POST",
dataType: "json",
contentType: "application/json;charset=UTF-8",
success:function(ret){
//console.log(ret);
//页面解析用户信息
builder_user(ret);
//解析分页
builder_page(ret);
},
});
后台的代码:
@RequestMapping(value="/getUser")
@ResponseBody //返回json
public User getJson(@RequestBody User user){//获得前台传递过来的json字符串并存储到pojo中,这种方式只接受ajax的post请求,如果是个get请求会报错。
System.out.println(user.getAddress());
return user;
}
1.1如果改为get请求:
前台报400
后台报:信息:
Error parsing HTTP request header
Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
1.2、如果ajax不加contentType: "application/json;charset=UTF-8",
前台报415错误:
后台报: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
1.3如果ajax请求传递是json对象而不是json字符串
前台报:
后台报:
org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unrecognized token 'id': was expecting ('true', 'false' or 'null')
at [Source: java.io.PushbackInputStream@67a5de27; line: 1, column: 4]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'id': was expecting ('true', 'false' or 'null')
at [Source: java.io.PushbackInputStream@67a5de27; line: 1, column: 4]
(2)利用HttpServletRequest request请求来获得前台的ajax传递过来的json数据
前台代码:
$.ajax({
url:"http://127.0.0.1:8080/SSM_maven/GetJson",
data:data,
type:"POST",
dataType: "json",
success:function(ret){
//console.log(ret);
//页面解析用户信息
builder_user(ret);
//解析分页
builder_page(ret);
},
});
后台的代码:
@RequestMapping("/GetJson")
@ResponseBody //返回json
public User GetJson(HttpServletRequest request){
User user = CommonUtils.toBean(request.getParameterMap(), User.class);//将request中的数据全部封装到bean中。
System.out.println(user.getAddress());
return user;
}
在这个过程中写了将request包含的数据直接封装到bean中的工具类,具体建立了CommonUtils和DateConverter两个类
CommonUtils.class代码
package cn.zzu.util;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
/**
* 小小工具
*将request中数据直接加载到bean中
*
*/
public class CommonUtils {
/**
* 返回一个不重复的字符串
* @return
*/
public static String uuid() {
return UUID.randomUUID().toString().replace("-", "").toUpperCase();
}
/**
* 把map转换成对象
* @param map
* @param clazz
* @return
*
* 把Map转换成指定类型
*/
@SuppressWarnings("rawtypes")
public static <T> T toBean(Map map, Class<T> clazz) {
try {
/*
* 1. 通过参数clazz创建实例
* 2. 使用BeanUtils.populate把map的数据封闭到bean中
*/
T bean = clazz.newInstance();
ConvertUtils.register(new DateConverter(), java.util.Date.class);
BeanUtils.populate(bean, map);
return bean;
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
DateConverter.class类的代码
package cn.zzu.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.apache.commons.beanutils.Converter;
/**
* 把String转换成java.util.Date的类型转换器
* @author qdmmy6
*
*/
public class DateConverter implements Converter{
@SuppressWarnings("rawtypes")
public Object convert(Class type, Object value) {
if(value == null) return null;//如果要转换成值为null,那么直接返回null
if(!(value instanceof String)) {//如果要转换的值不是String,那么就不转换了,直接返回
return value;
}
String val = (String) value;//把值转换成String
// 使用SimpleDateFormat进行转换
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(val);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
总结:第二种方式相对比较好些,对于前台的ajax请求的限制相对较少,后台获取的前台传递过来的参数相对容易灵活。