【问题标题】:Returning a list from a POST request in Spring using AJAX使用 AJAX 从 Spring 中的 POST 请求中返回列表
【发布时间】:2017-05-12 21:34:19
【问题描述】:

我目前在页面上有一个 POST 请求来检索课程列表。

$.ajax({
    headers: { 
      'Accept': 'application/json',
      'Content-Type': 'application/json' 
    },
    'type': 'POST',
    'url': '/search/request',
    'data': JSON.stringify(data),
    'dataType': 'json'
});

控制器中对应的方法返回一个教训列表:

@Controller
@EnableWebMvc
public class SearchController {
    // Some other methods

    @RequestMapping(value = "/search/request",  method = RequestMethod.POST)
    public @ResponseBody
    List<Lesson> search_lessons(@CookieValue("token") String token, @RequestBody SearchQuery query) {
        try {
            // Grab the user.

            // TODO: Implement search logic.
            List<Lesson> searchedLessons = lessonService.get_main_lessons_by_user(user);
            System.out.println(searchedLessons.size());
            return searchedLessons;
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }
    }
}

当我提出请求时,它会点击System.out.println(searchedLessons.size());,所以我知道正在填充列表。但是,进行 AJAX 调用会导致 500 错误,并且不会引发异常。如何让 Spring 返回此列表?

编辑:这是Lesson的结构

package com.dolphinblue.models;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Index;

import java.util.*;
/**
 * Created by FreddyEstevez on 3/21/17.
 * Represent model for lessons
 */
@Entity
public class Lesson implements Comparable<Lesson>{

    @Id private Long lesson_id;
    private Long index;
    private String title;
    @Index private String user_id; //user who is working on the lesson
    @Index private String creator_id; //user who created the lesson
    private List<Key<Task>> tasks; //holds lists of tasks ids for this lesson
    private double percent_complete; // Hold the percent of task the user has completed
    @Index private boolean shared;
    @Index private  boolean site_owned;
    private Key<Lesson> original_lesson;
    private String description;
    private int rating;
    //Date when lesson was last edited or changed.
    private Date last_edited;
    //Date when this lesson was last access by user working on it
    private Date last_accessed;

`

【问题讨论】:

  • 类路径上有杰克逊吗?一堂课的结构是什么?是否有任何可能发生的延迟加载?你看到有什么记录吗?您是否尝试过添加异常处理程序?
  • Jackson 在类路径中,因为它成功地序列化了SearchQuery 对象。编辑评论以添加课程结构。鉴于它在 return 语句之前提示 print 语句,因此 searchedLessons 在返回之前已经加载。没有记录任何内容,并且该方法已包含异常处理。
  • 那个 catch 块不会捕获在我怀疑正在发生的返回序列化期间发生的异常。任务或 original_lesson 是否延迟加载?
  • 我猜他们可能是这样,因为去掉这些字段会导致成功的序列化。我不认为 Jackson 能够序列化 Objectify 键。

标签: java ajax spring google-app-engine jackson


【解决方案1】:

因此,使用 Objectify Keys 删除任何字段允许对象序列化。

【讨论】:

    猜你喜欢
    • 2014-11-24
    • 2015-01-05
    • 2022-01-20
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 2015-09-22
    相关资源
    最近更新 更多