[刘阳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;
    }
    
}
复制代码

 源码下载:https://pan.baidu.com/s/1eSDZwFg

posted @   子墨老师  阅读(1066)  评论(0编辑  收藏  举报
编辑推荐:
· 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代理 了,记录一下
点击右上角即可分享
微信分享提示