欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-20 20:36:28
下面是官方文档对于@responsebody注解的解释: mapping the response body with the @responsebody ann...

下面是官方文档对于@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> 

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

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

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

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

控制器代码:

@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); 
      }); 
    }); 

运行返回例子:

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

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