查看: 273|回复: 0

[Java学习] Springmvc 4.x利用@ResponseBody返回Json数据的方法

发表于 2018-5-5 09:30:20

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

  1. Mapping the response body with the @ResponseBody annotation
  2. 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:
  3. @RequestMapping(path = "/something", method = RequestMethod.PUT)
  4. @ResponseBody
  5. public String helloWorld() {
  6. return "Hello World";
  7. }
  8. The above example will result in the text Hello World being written to the HTTP response stream.
  9. 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. <bean
  2. class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  3. <property name="messageConverters">
  4. <list>
  5. <ref bean="mappingJackson2HttpMessageConverter" />
  6. </list>
  7. </property>
  8. </bean>
  9. <bean id="mappingJackson2HttpMessageConverter"
  10. class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
  11. <property name="supportedMediaTypes">
  12. <list>
  13. <value>text/html;charset=UTF-8</value>
  14. <value>text/json;charset=UTF-8</value>
  15. <value>application/json;charset=UTF-8</value>
  16. </list>
  17. </property>
  18. </bean>
复制代码

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

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

控制器代码:

  1. @RequestMapping("House/ClassManager/addByAjax")
  2. @ResponseBody
  3. public HanBlog_Class ClassManager_addByAjax(HttpServletRequest request){
  4. if(request.getSession().getAttribute("hanblog_uid")==null) return null;
  5. HanBlog_Class objClass=new HanBlog_Class();
  6. return objClass;
  7. }
复制代码

jquery代码:

  1. //|增加
  2. $("#hanblog_add_btn").click(function(){
  3. var classname=$("#add_input_name").val();
  4. var classintroduction=$("#add_input_introduction").val();
  5. alert("分类名称:"+classname+"分类介绍:"+classintroduction);
  6. $.get("<c:url value="/House/ClassManager/addByAjax.do" />",function(result){
  7. alert(result);
  8. });
  9. });
复制代码

运行返回例子:

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



回复

使用道具 举报