[刘阳Java]_Spring MVC如何发送json数据_第4讲
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; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下