SpringMVC在发送json数据非常的方便,而且根本不用去手动装配json数据的转换。只要保证如下几个配置关键点即可
- 首先导入jackson-core.jar, jackson-annotation.jar, jackson-databind.jar,此包支持json格式数据转换。也是SpringMVC中默认依赖的包
- 在springmvc.xml配置文件中添加<mvc:annotation-driven/>
- 在控制器方法上编写@ResponseBody注解
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:annotation-driven></mvc:annotation-driven> <context:component-scan base-package="com.gxa.spmvc.controller"></context:component-scan> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp"></bean> </beans>
package com.gxa.spmvc.controller; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.gxa.spmvc.entity.Student; /** * SpringMVC的控制器(业务控制器) * 定义的方法就是一个请求处理的方法 * @author caleb * */ @Controller @RequestMapping("/user") public class TestController { /** * @ResponseBody 将实体转换成Json数据 * 具备两个条件 * 1. 导入jackson-core.jar, jackson-annotation.jar, jackson-databind.jar * 2. springmvc-web.xml 添加 <mvc:annotation-driven/> * @return */ @ResponseBody @RequestMapping("/m08") public Student m08() { Student student = new Student(); student.setId(1001); student.setSname("liu"); student.setT_id(2001); return student; } }