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

发布时间:2020-10-23 23:48:24 作者:涵涵YH
来源:脚本之家 阅读:121

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

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

推荐阅读:
  1. SpringMVC处理Put或Delete请求报错及解决方法
  2. SpringMVC接收和响应json数据的方法有哪些

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springmvc4 @responsebody json

上一篇:基于Java语言MD5加密Base64转换方法

下一篇:解决pyshp UnicodeDecodeError的问题

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》