java - 无法从 Controller 访问主干模型属性

标签 java spring-mvc backbone.js

我遇到了有关 BackboneJS 和 spring mvc Controller 之间交互的错误。将模型添加到集合列表时,我无法访问模型属性。我的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 Controller ,其定义如下:

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";

    }


}

Controller 方法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.

我无法解决这个问题。

最佳答案

您需要一个 Java 类来表示 spring 可以将值映射到的 JSON 对象。 @RequestParam 用于映射来自请求的查询字符串参数,而 REST 和主干则不是这样的。

您的代码应类似于:

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

Spring 将从 JSON 请求中设置 todo 中的值

关于java - 无法从 Controller 访问主干模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50129261/

相关文章:

java - Google Voice 接收新来电通知

java - 如何在存储访问框架中设置不常见的文件扩展名?

java - 更改 DecimalFormat 语言环境

java - 如何使用 iText 将图形绘制为 PDF?

java - getDeclaringClass 导致未能延迟初始化异常

javascript - 主干 View 无法使用 requirejs 扩展

javascript - Backbone-relational.js + Backbone.View(s)

java - 文件解析代码给了我异常而不是数字,文件写入代码给出了乱码而不是数字

java - 在 Spring MVC 应用程序属性文件中使用阿拉伯字符串

backbone.js - 在 Backbone 单页应用程序中跟踪主题标签路由的事件(通过谷歌分析)