秀外慧中的springMVC(五)---输入和输出使用json格式方式

本文介绍SpringMVC中如何使用注解处理JSON数据,包括@ResponseBody、@RequestBody等的运用,以及不同转换器如MappingJacksonHttpMessageConverter的作用。同时展示了如何配置SpringMVC以支持JSON数据交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.转换需要的注解

在springmvc中存在如下三个重要的注解来对传入传出的数据进行转换

@ResponseBody---将内容或对象作为 HTTP 响应正文返回,并调用适合HttpMessageConverter的Adapter转换对象可以转换为html,写入输出流

@RequestBody---将HTTP请求正文转换为适合的HttpMessageConverter对象

@PathVariable ---指定请求的参数,传入注解的字段

2.springmvc各个转换器

StringHttpMessageConverter
          字符串转换器.支持所有 (text/*)和 Content-Type of text/plain相互转换.

FormHttpMessageConverter
          from数据转换器  application/x-www-form-urlencoded.将 Form data 相互转换 MultiValueMap<String, String>.

ByteArrayMessageConverter
          流数据转换器. (*/*), and writes with a Content-Type of application/octet-stream.

MarshallingHttpMessageConverter
         xml转换器. (text/xml) and (application/xml).

MappingJacksonHttpMessageConverter
         json的转换器. (application/json).

SourceHttpMessageConverter
         javax.xml.transform.Source 类型的转换器. 只能是 DOMSource, SAXSource, 和 StreamSource被支持, 支持 (text/xml) 和 (application/xml).

BufferedImageHttpMessageConverter
         java.awt.image.BufferedImage 类型的转换器,通过流
 

3.springmvc使用json传递数据

需要加入jacksonjar包
jackson-core-2.2.3.jar
jackson-annotations-2.2.3
jackson-databind-2.2.3.jar


web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
  	<servlet-name>springmvc</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>springmvc</servlet-name>
  	<url-pattern>*.do</url-pattern>
  </servlet-mapping>
  
  	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/springmvc-servlet.xml</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
  
</web-app>

springmvc-servlet.xml 

<?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:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/tx 
     	   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     	   http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

	<context:component-scan base-package="com.mvc"></context:component-scan>
	<mvc:annotation-driven />
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.UrlBasedViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView"></property>
		<property name="prefix" value="/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
<!--配置json的转换器,使用<mvc:annotation-driven />则默认就会自动使用对应的转换器不必配置
 <bean 
      class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
        <property name="messageConverters">  
            <list>  
                <bean 
                    class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">  
                    <property name="supportedMediaTypes">  
                        <list>  
                            <value>application/json;charset=UTF-8</value>  
                        </list>  
                    </property>  
                </bean>  
            </list>  
        </property>  
    </bean>  --> 
	
</beans>
Person类

package org.senssic.springmvc;

public class Person {
	private String name;
	private int age;

	@Override
	public String toString() {
		return "名字:" + name + "年龄:" + age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	};

}

Controller控制类:

package org.senssic.springmvc;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
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.ResponseBody;

@Controller
public class JSONController {

	@RequestMapping(value = "/json", method = RequestMethod.GET)
	public @ResponseBody
	// 返回输出为json
	Person getShopInJSON(@RequestBody Person person/* 请求参数为json并转换为Person */,
			@PathVariable("name"/* 请求参数 */) String str/* 匹配参数 */) {

		// 测试数据
		Person per = new Person();
		System.out.println("Shop");
		per.setName("Eric");
		per.setAge(20);

		return per;

	}

}




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值