多语言展示
当前在线:368今日阅读:84今日分享:32

SpringMVC中JSON数据HttpMessageConverter原理

SpringMVC中JSON数据HttpMessageConverter原理
工具/原料
1

SpringMVC

2

eclipse

方法/步骤
1

HttpMessageConverter是Spring3.0新添加的一个接口,负责将请求信息转换成一个对象,将对象输出为响应信息。

2

SpringMVC默认加载了HttpMessageConverter的6个实现类。使用HttpMessageConverter将请求信息转化并绑定到处理方法的入参中或将响应结果转为对应类型的响应信息,Spring提供了两种途径:1、使用@RequestBody/@ResponseBody对处理方法进行标注2、使用HttpEntity、ResponeEntity作为处理的入参或返回值。

3

SpringMVC使用具体的HttpMessageConverter实现类是根据实际的入参或者返回值来判断的。

4

在jsp页面新建一个表单提交页面。       

                Test JSON       

               
                file:                                desc:                                       

5

在SpringMVC中实现文件表单页面的提交。package com.gwolf.springmvc.handlers;import java.util.Collection;import java.util.Date;import java.util.Map;import javax.validation.Valid;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.validation.BindingResult;import org.springframework.validation.FieldError;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestAttribute;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.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import com.gwolf.springmvc.dao.DepartmentDao;import com.gwolf.springmvc.dao.EmployeeDao;import com.gwolf.springmvc.domain.Employee;@Controllerpublic class EmployeeHandler {        @Autowired        private EmployeeDao employeeDao;                @Autowired        private DepartmentDao departmentDao;                                @RequestMapping('/testHttpMessageConverter')        @ResponseBody        public String testConverter(@RequestBody String body) {                System.out.println(body);                return 'helloworld!'+new Date();        }                }

6

启动tomcat,查看程序提交的结果和返回json数据的结果。

推荐信息