Springmvc 4.x利用@ResponseBody返回Json数据的方法
时间:2021-04-13 09:15:36|栏目:JAVA代码|点击: 次
下面是官方文档对于@ResponseBody注解的解释:
Mapping the response body with the @ResponseBody annotation
The @ResponseBody annotation is similar to @RequestBody. This annotation can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name). For example:
@RequestMapping(path = "/something", method = RequestMethod.PUT)
@ResponseBody
public String helloWorld() {
return "Hello World";
}
The above example will result in the text Hello World being written to the HTTP response stream.
As with @RequestBody, Spring converts the returned object to a response body by using an HttpMessageConverter. For more information on these converters, see the previous section and Message Converters.
@ResopnseBody注解能够 直接把 控制器返回变量(String)直接 返回给浏览器,也可以通过配置 后,把 对象 序列化成Json数据返回给浏览器!如果为 null 就会返回空白。
怎么配置呢 ?需要配置MessageConverter:
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJackson2HttpMessageConverter" />
</list>
</property>
</bean>
<bean id="mappingJackson2HttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>text/json;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
下面贴出在官方文档中的位置:

这个需要jackson jar包支持,需要 jackson-annotations,jackson-core,jackson-databind三个包,:

控制器代码:
@RequestMapping("House/ClassManager/addByAjax")
@ResponseBody
public HanBlog_Class ClassManager_addByAjax(HttpServletRequest request){
if(request.getSession().getAttribute("hanblog_uid")==null) return null;
HanBlog_Class objClass=new HanBlog_Class();
return objClass;
}
jquery代码:
//|增加
$("#hanblog_add_btn").click(function(){
var classname=$("#add_input_name").val();
var classintroduction=$("#add_input_introduction").val();
alert("分类名称:"+classname+"分类介绍:"+classintroduction);
$.get("<c:url value="/House/ClassManager/addByAjax.do" />",function(result){
alert(result);
});
});
运行返回例子:

上一篇:Maven 项目生成jar运行时提示“没有主清单属性”
栏 目:JAVA代码
下一篇:详解spring cloud分布式整合zipkin的链路跟踪
本文标题:Springmvc 4.x利用@ResponseBody返回Json数据的方法
本文地址:http://www.codeinn.net/misctech/100591.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




