无法从控制器

时间:2018-05-02 07:31:28

标签: java spring-mvc backbone.js

我遇到了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 需要 taskName 类别等参数。在向 taskList 添加新的任务时,也会提到这些属性。在服务器上执行上述代码时,我从浏览器控制台收到错误定义如下:

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

服务器端错误存在如下:

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

我无法解决此问题。

1 个答案:

答案 0 :(得分:1)

您需要一个Java类来表示Spring可以将值映射到的JSON对象。 @RequestParam用于映射请求中的查询字符串参数,而REST和骨干不是这种情况。

您的代码应该类似于:

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

和spring将根据JSON请求

设置todo中的值