您的位置:首页 > 编程语言 > Java开发

springmvc 4 返回json数据

2016-06-23 16:09 501 查看
1.导入相关jar包

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.5.4</version>
</dependency>

2.配置servlet.xml文件
<mvc:annotation-driven /> <!-- mvc驱动 -->
<context:component-scan base-package="com" /> <!-- 扫描的包 -->

<bean id="stringConverter"
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value> 字符串编码
</list>
</property>
</bean>
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="stringConverter" />
<ref bean="jsonConverter" />
</list>
</property>
</bean>

3.在函数方法上添加@ ResponseBody注解
@RequestMapping("/getjson")
@ResponseBody
public Object getJson() {
UserInfo user = new UserInfo();
user.setAge(12);
user.setName("sss");
user.setSex(1);
BaseJson baseJson = new BaseJson();
baseJson.setCode("1");
baseJson.setMsg("哈哈哈哈哈哈");
baseJson.setData(user);
return baseJson;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring mvc