无法从控制器访问 backbone 模型属性

Unable to access backbone Model properties from controller

我遇到了有关 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映射到一个springmvc控制器,定义如下:

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 添加新的 task 时也提到了这些属性。在服务器上执行上述代码时,我从浏览器控制台收到错误定义如下:

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

服务器端存在如下错误:

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

我无法解决这个问题。

您需要一个 Java class 来表示 JSON 对象 spring 可以将值映射到。 @RequestParam 用于从请求映射查询字符串参数,REST 和 backbone 不是这种情况。

您的代码应该类似于:

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

和 spring 将从 JSON 请求

中设置 todo 中的值