zoukankan      html  css  js  c++  java
  • 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错误
  • 相关阅读:
    python 10大算法之一 LinearRegression 笔记
    Android+openCV 动态人脸检测
    ubuntu+github配置使用
    Android+openCV人脸检测2(静态图片)
    Android CameraManager 类
    Android人脸检测1(静态图片)
    Android读写配置2
    Git分支(branch)
    mvn
    git 停止跟踪某一个文件
  • 原文地址:https://www.cnblogs.com/zyxiaohuihui/p/9088126.html
Copyright © 2011-2022 走看看