|
这几年都在搞前后端分离、RESTful风格,我们项目中也在这样用。前几天有人遇到了解析JSON格式的请求数据的问题,然后说了一下解析的方式,今天就写篇文章简单的分析一下后台对于JSON格式请求数据是怎么解析的。
先把例子的代码贴出来:
前端
<input type="button" value="测试JSON数据" onclick="testJSON()" />
<script type="text/javascript">
function testJSON() {
$.ajax({
type: "POST",
url: "/testJson",
contentType: "application/json",
dataType: "json",
data: JSON.stringify({"name":"张三"}),
success: function (jsonResult) {
alert(jsonResult);
}
});
}
</script>
后台处理代码如下:
@RequestMapping(value ="testJson")
public String testJson(@RequestBody Map name, HttpServletRequest request){
System.out.println(name);
return "jsonp";
}
这里需要注意的是:要在参数对象上加上@RequestBody注解,这个一定不能少,后台在接收JSON数据的时候一定要用自定义的对象或者Map对象去接收,不要用JDK中的简单对象(String/Integer/Long)来接收。
接下来我再把抓出来的http请求贴一下:
Content-Type:application/json

这里需要注意的是:Request Payload中的格式一定要和上图一致,其他格式SpringMVC会解析不出来。
OK,如上的代码就可以搞定一个JSON请求数据的解析了。下面我们来分析一下SpringMVC是怎么处理JSON请求的。
SpringMVC处理请求的简单时序图如下:

正常情况下,一个请求在SpringMVC中一般会调用doDispatch这个方法,我们进入到这个方法中直接跳到
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
这一行,这一行上面的内容我们以后再找机会分析。
ha.handle这个方法会调用org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter中的handle方法,这个方法里面很简单,就是调用了handleInternal这个方法,代码如下:
public final ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
return handleInternal(request, response, (HandlerMethod) handler);
}
而handleInternal这个方法调用的是org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter中的handleInternal方法,我们进入到这个方法中看看这个方法中都干了一些什么事:
@Override
protected ModelAndView handleInternal(HttpServletRequest request,
HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {
ModelAndView mav;
checkRequest(request);//检查是不是所支持的请求类型、是不是要求session
// Execute invokeHandlerMethod in synchronized block if required.
if (this.synchronizeOnSession) {//session中是不是要求同步执行
HttpSession session = request.getSession(false);
if (session != null) {
Object mutex = WebUtils.getSessionMutex(session);
synchronized (mutex) {//同步执行方法调用
mav = invokeHandlerMethod(request, response, handlerMethod);
}
}
else {
// No HttpSession available -> no mutex necessary
mav = invokeHandlerMethod(request, response, handlerMethod);
}
}
else {
// No synchronization on session demanded at all...
mav = invokeHandlerMethod(request, response, handlerMethod);//这三个invokeHandlerMethod调用的是同一个方法
}//缓存的设置
if (!response.containsHeader(HEADER_CACHE_CONTROL)) {
if (getSessionAttributesHandler(handlerMethod).hasSessionAttributes()) {
applyCacheSeconds(response, this.cacheSecondsForSessionAttributeHandlers);
}
else {
prepareResponse(response);
}
}
return mav;
}
在上面的这个方法中我们需要关注的是invokeHandlerMethod这个方法。invokeHandlerMethod这个方法有点复杂,这个方法中干了很多的事,像创建数据验证类、创建方法处理类、模型视图容器等。在这里我们先忽略这些,直接跳到
invocableMethod.invokeAndHandle(webRequest, mavContainer);
这里。这个方法在org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod中。在这个方法中我们只关注第一句话:
Object returnValue = invokeForRequest(webRequest, mavContainer-est = webRequest.getNativeRequest(HttpServletRequest.class);
ServletServerHttpRequest inputMessage = new ServletServerHttpRequest(servletRequest);
//从请求输入流中解析出参数的值
Object arg = readWithMessageConverters(inputMessage, methodParam, paramType);
if (arg == null) {
if (checkRequired(methodParam)) {//校验参数是不是必须的
throw new HttpMessageNotReadableException("Required request body is missing: " +
methodParam.getMethod().toGenericString());
}
}
return arg;
}
我们重点要看的是org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver中的readWithMessageConverters方法。
这个方法很长,在这个方法中会获取ContentType、参数的类型、Method、重新封装Request等等的操作。我们需要关注这三行代码:
inputMessage = getAdvice().beforeBodyRead(inputMessage, param, targetType, converterType);
body = genericConverter.read(targetType, contextClass, inputMessage);[1]
body = getAdvice().afterBodyRead(body, inputMessage, param, targetType, converterType);
为参数赋值的是[1]这行代码。这里调用的是org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter中的read方法,代码如下:
@Override
public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
/获取Java中的类型
JavaType javaType = getJavaType(type, contextClass);
return readJavaType(javaType, inputMessage);//按照Java的类型,为参数赋值
}
private Object readJavaType(JavaType javaType, HttpInputMessage inputMessage) {
try {
if (inputMessage instanceof MappingJacksonInputMessage) {
Class<?> deserializationView = ((MappingJacksonInputMessage) inputMessage).getDeserializationView();
if (deserializationView != null) {
return this.objectMapper.readerWithView(deserializationView).forType(javaType).
readValue(inputMessage.getBody());
}
}
return this.objectMapper.readValue(inputMessage.getBody(), javaType);//[1]调用Jackson中的方法,解析Body的内容,赋值为java的类型
}
catch (IOException ex) {
throw new HttpMessageNotReadableException("Could not read document: " + ex.getMessage(), ex);
}
}
this.objectMapper.readValue这个方法会掉到Jackson相关的jar中。再往下跟的话还有很深,说实在的里面有很多的方法我还没看明白,所以我们就不继续往下走了。这个方法中大致干的事是按照相应的编码读取HTTP请求中请求体里的内容,由于是JSON格式的,所以又会把JSON格式的数据转换为传入进去的Java类型对象。
后记:
如果我们知道请求格式是JSON的话,我们可以自己写一个简单的请求体的解析,但是在项目中最好别这样做。代码如下:
@RequestMapping(value ="testJson")
public String testJson(HttpServletRequest request){
try {
InputStream inputStream = request.getInputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int flag = 0;
while ((flag = inputStream.read(bytes)) > 0){
byteArrayOutputStream.write(bytes,0,flag);
}
System.out.println(new String(byteArrayOutputStream.toByteArray(),request.getCharacterEncoding()));
} catch (IOException e) {
e.printStackTrace();
}
return "jsonp";
}
请求信息如下:

后台输出结果如下:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持社区。 |