• Vue入门(四)——Axios向SpringMVC传数据


    在实际业务需求中,经常会出现前台传表单或者对象到后台,后台Handler接受并转换成对应的POJO以供业务代码使用

    此时在SpringMVC框架中就要用到@RequestBody注解,该注解用于将请求中的JSON对象转换成对应的POJO类的属性;

    后台框架中使用该注解,需要在spring-mvc的配置文件中加入如下配置依赖(jackson-core,jackson-databind,jackson-annotations):

    <mvc:annotation-driven>
            <!--设置全局时间格式化 -->
            <mvc:message-converters>
                <bean
                    class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <property name="objectMapper">
                        <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                            <property name="dateFormat">
                                <bean class="java.text.SimpleDateFormat">
                                    <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />
                                </bean>
                            </property>
                        </bean>
                    </property>
                </bean>
            </mvc:message-converters>
        </mvc:annotation-driven>

    Controller:

    @RequestMapping(value = "/add/blog", method = RequestMethod.POST, produces = {"application/json;charset=utf-8"})
        public void addBlog(@RequestBody Blog blog, HttpServletRequest request, HttpServletResponse response){
            blogServicesImpl.save(blog);
            Result result = new Result();
            result.setSuccess(true);
            this.print(result, response);
        }

    Vue页面:

    this.$ajax({
              method: 'POST',
              url: '/api/mobile/add/blog',
              data: JSON.stringify(data),
              headers: {
                'Content-Type': 'application/json;charset=UTF-8'
              }
            }).then(response => {
              debugger;
              var result = response.data;
              if (result.success) {
                var list = result.list;
                for(var i=0; i<list.length; i++){
                  var blog = {};
    
                  blog.title = list[i].blogTitle;
                  blog.bref = list[i].blogSummary;
                  that.collect.push(blog);
                }
    
              } else {
                this.logs = []
                this.$message.error(result.message)
              }
            }).catch(error => {
              this.$message.error(error.message)
            })

    注意,这里的前台请求和Controller中获取Request的请求方式要一致,都为

    application/json;charset=UTF-8,

    否则请求415错误
  • 相关阅读:
    kill all process on a specific port on linux 码农
    rxjs 学习系列二(环境搭建) 码农
    实拍图与摄相头自动合成软件(效果) 码农
    js中for in的用法
    Android sdk资源包res里面的drawable(ldpi、mdpi、hdpi、xhdpi、xxhdpi)
    js中addEventListener中第3个参数
    【agc006f】Blackout
    Trie&可持久化Trie
    【agc014d】Black and White Tree
    【agc009b】Tournament
  • 原文地址:https://www.cnblogs.com/zyxiaohuihui/p/9088126.html
Copyright © 2020-2023  润新知