zoukankan      html  css  js  c++  java
  • SpringMVC的JSON数据交互(七)-@Response,@RestController,@RequestBody用法

    1.@RequestBody   (自动将请求的数据封装为对象)

    作用:

    @RequestBody注解用于读取http请求的内容(字符串),通过springmvc提供的HttpMessageConverter接口将读到的内容(json数据)转换为java对象并绑定到Controller方法的参数上。

    传统的请求参数:

    itemEdit.action?id=1&name=zhangsan&age=12

    现在的请求参数:

    使用POST请求,在请求体里面加入json数据

    {

    "id": 1,

    "name": "测试商品",

    "price": 99.9,

    "detail": "测试商品描述",

    "pic": "123456.jpg"

    }

    2.@ResponseBody

    作用:

    @ResponseBody注解用于将Controller的方法返回的对象,通过springmvc提供的HttpMessageConverter接口转换为指定格式的数据如:json,xml等,通过Response响应给客户端

    总结:

      在controller中我们可以在方法上面添加@ResponseBody注解,这样我们返回实体对象或者字符串时,就会自动转换成json对象传给前端。在spring4.0后,@ResponseBody又可以加在类上,表示该类中的所有方法都加有@ResponseBody,很方便。另一种方式是使用@RestController注解在类上,作用等于@Controller与@ResponseBody同时加在类上,这也是最方便的一种方式。要让@ResponseBody在类上也起作用,需要在springmvc配置文件中加上<mvc:annotation-driven />这一行配置才可以。而@ResponseBody使用在方法上,则不用添加该配置也可以使用。也就是说springmvc默认只支持@ResponseBody在方法上使用,不支持在类上的使用。

      在实际项目中,我们可能会将后台管理项目与app的后台放在一个项目里面,这样就等于是两个后台共用一套springmvc的配置文件。但是app后台的controller都是返回json信息的,而后台管理是用来返回jsp界面的,会有点混乱。这种情况下,我们需要同时配置<mvc:annotation-driven />和viewResolver,这样的话,app后台的controller都加上@RestController即可,而后台管理的controller则不要@ResponseBody和@RestController,只返回字符串格式的jsp文件名即可。这样就可以两不耽误,两个项目合在一起开发了。

    查看RestController的源码:  (是一个组合注解)

    /*
     * Copyright 2002-2014 the original author or authors.
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *      http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    
    package org.springframework.web.bind.annotation;
    
    import java.lang.annotation.Documented;
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    import org.springframework.stereotype.Controller;
    
    /**
     * A convenience annotation that is itself annotated with {@link Controller @Controller}
     * and {@link ResponseBody @ResponseBody}.
     * <p>
     * Types that carry this annotation are treated as controllers where
     * {@link RequestMapping @RequestMapping} methods assume
     * {@link ResponseBody @ResponseBody} semantics by default.
     *
     * @author Rossen Stoyanchev
     * @author Sam Brannen
     * @since 4.0
     */
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Controller
    @ResponseBody
    public @interface RestController {
    
        /**
         * The value may indicate a suggestion for a logical component name,
         * to be turned into a Spring bean in case of an autodetected component.
         * @return the suggested component name, if any
         * @since 4.0.1
         */
        String value() default "";
    
    }

    例如:

    package cn.xm.jwxt.controller.common;
    
    import cn.xm.jwxt.bean.common.Dictionary;
    import cn.xm.jwxt.service.common.DictionaryService;
    import org.apache.log4j.Logger;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.sql.SQLException;
    import java.util.List;
    
    /**
     * 字典controller
     */
    
    @RequestMapping("/dictionary")//基本的映射路径
    //@ResponseBody//所有方法返回都是以JSON形式返回
    //@Controller//控制层代码
    @RestController//这个注解等于@ResponseBody+@Controller
    public class DictionaryController {
        @Autowired
        private DictionaryService dictionaryService;
        private Logger logger = Logger.getLogger(DictionaryController.class);
    
        @RequestMapping("/getDictionaryTree")
        public List<Dictionary> getDictionaryTrees() {
            List<Dictionary> dictionaryTree = null;
            try {
                dictionaryTree =  dictionaryService.getDictionaryTree();
            } catch (SQLException e) {
                logger.error("查询字典树出错!",e);
            }
            return dictionaryTree;
        }
    
    
    }

    3.请求json,响应json实现:

    3.1. 加入jar包

    如果需要springMVC支持json,必须加入json的处理jar

    我们使用Jackson这个jar,如下图:

    3.1 JSP页面ajax请求

    <script type="text/javascript">
    
    $(function(){
        var param='{"id": 1,"name": "测试商品","price": 99.9,"detail": "测试商品描述","pic": "123456.jpg"}';
        $.ajax({
            url:"${pageContext.request.contextPath }/json.action",
            async:true,
            type:"POST",
            data:param,
            contentType : "application/json;charset=UTF-8",//发送数据的格式
            success: function(data){
                  alert(data.name);
                },
            error:function(){
                alert("请求失败");
                },
            dataType:"json"    //回掉数据格式
        });
        
    })
    </script>

    3.2.处理ajax请求的controller

    @RequestMapping(value = "/json.action")
        public    @ResponseBody Items json(@RequestBody Items items){
    //        设置@RequestBody后子发动将ajax请求封装为对象
            System.out.println(items);
            
    //        设置@ResponseBody后自动将返回的数据封装为ajax
            return items;
        }
        

    3.3 配置json转换器

    如果不使用注解驱动<mvc:annotation-driven />,就需要给处理器适配器配置json转换器,参考之前学习的自定义参数绑定。

    在springmvc.xml配置文件中,给处理器适配器加入json转换器:

    <!--处理器适配器 -->
    
       <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    
          <property name="messageConverters">
    
          <list>
    
          <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
    
          </list>
    
          </property>
    
       </bean>
  • 相关阅读:
    i5ting_doc的安装和使用
    vscode—修改默认的shell
    cookie的相关知识
    这是一段有毒的js代码,求大神解释!!!
    BFC的触发条件
    替换元素与非替换元素
    css中em的使用方法
    误操作导致ps界面中的工具栏消失
    导航栏里面的li标签和a标签的配合使用
    记录一下 elmentui 循环复选框不能选中问题
  • 原文地址:https://www.cnblogs.com/qlqwjy/p/7246450.html
Copyright © 2011-2022 走看看