首页 > 解决方案 > 无法从控制器访问主干模型属性

问题描述

我遇到了关于 BackboneJS 和 spring mvc 控制器之间交互的错误。将模型添加到集合列表时,我无法访问模型属性。我的 JS 代码中容易出错的部分如下:

var Task = Backbone.Model.extend({
   defaults: {
     taskName: '',
     category:'',
     completed: false,
     dateCreated:0,
     dateCompleted:0
   }
 });



var TaskList = Backbone.Collection.extend({
   model: Task,
   url : "/todoCollection"
 });

// instance of the Collection
var taskList = new TaskList();


var TaskView = Backbone.View.extend({

   tagName: 'div',
   render: function(){


       var itemHTML = _.template($('script.itemview').html());

     this.$el.html(itemHTML(this.model.toJSON()));
     return this; // enable chained calls
   }

});

 var TaskCreateView = Backbone.View.extend({
     el : ".taskcreate",
     initialize : function(){
         this.render();
         this.input = this.$('#taskInput');
         this.categoryInput = this.$('#taskCategory');
         taskList.on('add', this.addAll, this);
         taskList.on('reset', this.addAll, this);
         taskList.fetch();
     },

     render : function(){
         var createListHTML = _.template($('script.create-task-view').html());
         this.$el.append(createListHTML);
         var createListHTML = _.template($('script.list-view').html());
         this.$el.append(createListHTML);
     },

     events: {
         'click button#createButton':'createTask'
     },

     createTask : function(e){

         if(this.input.val() == ''){
            alert("Task name expected");
            return;
         }

         if(this.categoryInput.val() == 'None'){
            alert("Enter valid category");
            return;
          }

         var newTask = {

             taskName: this.input.val().trim(),
             completed: false,
             category: this.categoryInput.val().trim()

         };


         taskList.create(newTask,{ wait: true });
         this.input.val(''); // clean input box
         this.categoryInput.val('None');

     },



     addOne: function(task){
         var view = new TaskView({model: task});
         $('#listDiv').append(view.render().el);
     },

     addAll: function(){
         this.$('#listDiv').html(''); // clean the todo list
         taskList.each(this.addOne, this);
     }


});

var TodoAppView = Backbone.View.extend({

    el: '#todoApp',

    initialize : function(){
      this.render();
    },

    render : function(){
        var appHTML = _.template($('script.appview').html());
        this.$el.append(appHTML);
        var taskCreateView = new TaskCreateView();
    }

});

var TodoApp1 = new TodoAppView();

TaskList 中的 url /todoCollection映射到一个 spring mvc 控制器,其定义如下:

package com.glider.controller;


import com.glider.model.Todo;
import com.glider.service.TodoService;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
public class TodoCollectionController {

    @Autowired
    TodoService service;

    @RequestMapping(value = "/todoCollection",method = RequestMethod.POST)
    @ResponseBody
    public String createTodo(@RequestParam(value = "taskName")String taskName,
                          @RequestParam(value = "category")String category){

        System.out.println("Method working");
        ObjectMapper objectMapper = new ObjectMapper();
        try {

            Todo todo =  service.create(taskName,category);
            String jsonInString = objectMapper.writeValueAsString(todo);
            return jsonInString;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";

    }

    @RequestMapping(value = "/todoCollection",method = RequestMethod.GET)
    @ResponseBody
    public String getAllTodo(){


        ObjectMapper objectMapper = new ObjectMapper();
        try {
            List<Todo> todoList = service.findAllTasks();
            String jsonInString = objectMapper.writeValueAsString(todoList);
            return jsonInString;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";

    }


}

控制器方法createTodo需要像taskNamecategory这样的参数。在向taskList添加新任务时也会提到这些属性。在服务器上执行上述代码时,我从浏览器控制台收到错误,定义如下:

jquery.min.js:4 POST http://localhost:8080/todoCollection 400 (Bad Request)

在服务器端存在如下错误:

HTTP Status 400 - Required String parameter 'taskName' is not present.

我无法解决这个问题。

标签: javaspring-mvcbackbone.js

解决方案


您需要一个 Java 类来表示 Spring 可以将值映射到的 JSON 对象。@RequestParam用于从请求中映射查询字符串参数,而 REST 和骨干网并非如此。

您的代码应类似于:

public String createTodo(@RequestBody Todo todo)){}

spring 将从todoJSON 请求中设置值


推荐阅读