Springmvc 4.x利用@ResponseBody返回Json数据的方法

2025-05-29 0 100

下面是官方文档对于@responsebody注解的解释:

?

1

2

3

4

5

6

7

8

9

10

11

12
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:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18
<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>

下面贴出在官方文档中的位置:

Springmvc 4.x利用@ResponseBody返回Json数据的方法

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

Springmvc 4.x利用@ResponseBody返回Json数据的方法

控制器代码:

?

1

2

3

4

5

6

7
@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代码:

?

1

2

3

4

5

6

7

8

9
//|增加

$("#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);

});

});

运行返回例子:

Springmvc 4.x利用@ResponseBody返回Json数据的方法

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:https://blog.csdn.net/u012997311/article/details/51982461

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Springmvc 4.x利用@ResponseBody返回Json数据的方法 https://www.kuaiidc.com/111765.html

相关文章

发表评论
暂无评论