下面是官方文档对于@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>下面贴出在官方文档中的位置:
这个需要jackson jar包支持,需要 jackson-annotations,jackson-core,jackson-databind三个包,:
控制器代码:
? 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); }); });运行返回例子:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/u012997311/article/details/51982461