Jackson @ResponseBody 上的内部服务器错误

2024-01-15

我只想将我的用户对象作为 JSON 返回,以供客户端的 ajax 调用使用。

这在某一时刻是有效的,经过一些更新(即,将应用程序更改为部署到/在 Jetty 中)后,现在就不行了。

我没有从代码中抛出异常,它返回得很好,但在尝试将对象转换为 JSON 时,似乎在 Jackson 的根代码中的某个地方发生了爆炸。

就像我说的,我没有遇到异常,我的 ajax 调用只是爆炸并显示错误代码“500,内部服务器错误”。

/* User contains information about a user of this site, that exists only
 * in the context of this site (no names, addresses).
 */
@Entity(name="User")
@Table(name="USER")
@NamedQuery(
    name="findUserByName",
    query="SELECT OBJECT(u) FROM User u WHERE u.name = :name"
)
public class User extends AuditableEntity implements Serializable {

private static final long serialVersionUID = -1308795024222223320L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="id")
private Long id;


@NotEmpty
@MinSkipEmpty(value=6)
@MaxSkipEmpty(value=32)
@Column(name="name", length=32)
private String name;

@NotEmpty
@MinSkipEmpty(value=4)
@MaxSkipEmpty(value=40)
@Column(name="password", length=40)
private String password;

@Column(name="salt", length=40)
private String salt;


@ManyToOne(fetch=FetchType.LAZY, cascade={CascadeType.PERSIST})
@JoinColumn(name="person_id")
private Person person;

@Column(name="last_login")
private Date lastLogin;

@ElementCollection(fetch=FetchType.EAGER)
@CollectionTable(name ="USER_AUTHORITY")
@Column(name="authority")
private List<Integer> authorities;


public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = (name == null ? name : name.trim());

}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = (password == null ? password : password.trim());
}

public String getSalt() {
    return salt;
}

public void setSalt(String salt) {
    this.salt = salt;
}

public Person getPerson() {
    return person;
}

public void setPerson(Person person) {
    this.person = person;
}

public Date getLastLogin() {
    return lastLogin;
}

public void setLastLogin(Date lastLogin) {
    this.lastLogin = lastLogin;
}

public List<Integer> getAuthorities() {
    return authorities;
}

public void setAuthorities(List<Integer> authorities) {
    this.authorities = authorities;
}

}

这是人实体

@Entity(name = "Person")
@Table(name = "PERSON")
public class Person extends AuditableEntity implements Serializable {

    private static final long serialVersionUID = -1308795024262635690L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    @NotEmpty
    @MaxSkipEmpty(value=64)
    @Column(name = "firstName", length=64)
    private String firstName;

    @NotEmpty
    @MaxSkipEmpty(value=64)
    @Column(name = "lastName", length=64)
    private String lastName;

    @NotEmpty
    @Email
    @MaxSkipEmpty(value=256,  message="")
    @Column(name = "email", length=256)
    private String email;

    @DateTimeFormat(pattern="MM/dd/yyyy")
    @NotNull(message = "Required field")
    @Column(name = "date")
    private Date birthday;

    @ManyToOne(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST })
    @JoinColumn(name = "location_id")
    private Location location;


    public Person() {

    }

    public Person(String firstName, String lastName) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Location getLocation() {
        return location;
    }

    public void setLocation(Location location) {
        this.location = location;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {

        return super.toString() + " name = " + firstName + " " + lastName
                + " id = " + id;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((firstName == null) ? 0 : firstName.hashCode());
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime * result
                + ((lastName == null) ? 0 : lastName.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Person other = (Person) obj;
        if (firstName == null) {
            if (other.firstName != null)
                return false;
        } else if (!firstName.equals(other.firstName))
            return false;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        if (lastName == null) {
            if (other.lastName != null)
                return false;
        } else if (!lastName.equals(other.lastName))
            return false;
        return true;
    }

}

@Entity(name = "Location")
@Table(name = "LOCATION")
public class Location extends AuditableEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    //name of person/place/thing

    @Column(name = "name", length=128)
    String name;

    //street address, p.o. box, company name, c/o
    @NotEmpty
    @MaxSkipEmpty(value=128)
    @Column(name = "line_1", length=128)
    String line1;

    // apt., suite, building, floor, entrance, etc.
    @Column(name = "line_2", length=128)
    String line2;

    @NotEmpty
    @MaxSkipEmpty(value=64)
    @Column(name = "city", length=64)
    String city;

    // state, providence, region
    @NotEmpty
    @MaxSkipEmpty(value=40)
    @Column(name = "state", length=40)
    String state;

    // postal code
    @NotEmpty
    @MaxSkipEmpty(value=16)
    @Column(name = "zip", length=16)
    String zip;

    @Column(name = "country")
    String country;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLine1() {
        return line1;
    }

    public void setLine1(String line1) {
        this.line1 = line1;
    }

    public String getLine2() {
        return line2;
    }

    public void setLine2(String line2) {
        this.line2 = line2;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getZip() {
        return zip;
    }

    public void setZip(String zip) {
        this.zip = zip;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    private static final long serialVersionUID = -178898928354655555L;
}

@RequestMapping(value="user/{documentId}", method=RequestMethod.GET)
public @ResponseBody User getUserForDocument( Model model,     @PathVariable("documentId") Long docId){

    Document doc = null;
    try{
        doc = dService.find(docId);
    }catch(Exception e){
        Logger logger = Logger.getLogger(DocumentController.class);
        logger.error(e.getMessage());
    }
    User user = doc.getUser();

    user.getPerson();
    user.getPerson().getLocation();
    return user;
}

@Repository()
public class DocumentDaoImpl implements DocumentDao {

    @PersistenceContext
    private EntityManager entityManager;

    @Transactional
    public Document find(Long id) {

        Document doc = entityManager.find(Document.class, id);

        Hibernate.initialize(doc.getUser());
        Hibernate.initialize(doc.getUser().getPerson());
        Hibernate.initialize(doc.getUser().getPerson().getLocation());

        return doc;
    }

    @SuppressWarnings("unchecked")
    @Transactional
    public List<Document> getUnassignedDocumentsForUser(User user) {

        Query query = entityManager.createQuery(new StringBuffer()
                .append("select d from Document d WHERE d.user = :user ")
                .append("AND NOT d IN( SELECT d from Book b, IN(b.docs) bd WHERE bd.id = d.id )")
                .append("").toString());
        query.setParameter("user", user);
        List<Document> tmp = (ArrayList<Document>) query.getResultList();
        for(Document doc : tmp){
            Hibernate.initialize(doc);
            Hibernate.initialize(doc.getUser());
            Hibernate.initialize(doc.getUser().getPerson());
            Hibernate.initialize(doc.getUser().getPerson().getLocation());
            entityManager.detach(doc);
            entityManager.detach(doc.getUser());
            entityManager.detach(doc.getUser().getPerson());
            entityManager.detach(doc.getUser().getPerson().getLocation());
        }
        return tmp;
    }

    @Transactional
    public Document save(Document doc) {

        if (doc.getId() == null) {
            entityManager.persist(doc);
            return doc;
        } else {
            return entityManager.merge(doc);
        }
    }

    public EntityManager getEntityManager() {
        return entityManager;
    }

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

}

错误异常解析器:

@Component
public class BWHandlerExceptionResolver extends SimpleMappingExceptionResolver implements InitializingBean{

    public void afterPropertiesSet() throws Exception {
        Properties props = new Properties();
        props.put(Exception.class.getName(),"error");
        this.setExceptionMappings(props);

    }

我经历了几乎相同的问题,但想知道到底是什么导致杰克逊失败, 而不是仅获取 500 个内部服务器,并且日志中的任何位置都没有异常堆栈跟踪。 检查了Spring MVC的源码后,第一个捕获异常的地方是 ServiceInvocableHandlerMethod.java(第109-116行):

...
try {
    returnValueHandlers.handleReturnValue(returnValue, getReturnType(), mavContainer, request);
} catch (Exception ex) {
    if (logger.isTraceEnabled()) {
        logger.trace(getReturnValueHandlingErrorMessage("Error handling return value", returnValue), ex);
    }
    throw ex;
}
...

handleReturnValue(...) 抛出异常,并在此处捕获但未打印出来,因为 logger.isTraceEnabled() 在默认配置中返回 false。 为了在日志中查看异常堆栈跟踪,我需要在上述类上启用 TRACE 级别日志记录。在我的特定情况下(我使用 log4j),这里是 log4j.properties 的相关部分:

...
log4j.logger.org.springframework.web.servlet.mvc.method.annotation=TRACE

log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Threshold=TRACE
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Jackson @ResponseBody 上的内部服务器错误 的相关文章

随机推荐

  • 如何重置 COMP_WORDBREAKS 而不影响其他完成脚本?

    当我实现 bash 自动完成功能时 有些事情让我感到困惑 我将把它放入 etc bash completion d 为了实现某些功能 我想删除分词字符冒号 来自变量 COMP WORDBREAKS并添加斜杠 开始于 COMP WORDBRE
  • 如何使用 iGraph 在 R 中挖掘主题

    我正在尝试使用该包在 R 中挖掘 3 节点图案igraph 我想检索图中每个单独顶点的图案数量 这在 graph motifs 函数中似乎不可能 因此 对于示例图 testGraph barabasi game 10 m 5 power 2
  • 将 TFS 项目转换为 git 存储库的最佳方法是什么

    我知道 VS2012 中对 git 的支持已经有了很多进展 我们目前有一个 Team Foundation Server 2012 更新 2 其中我们的所有项目都以经典 TFS 格式存储 我们希望从 TFS 迁移到纯 git repo 系统
  • 添加内存地址错误

    这无法在 VSC 2008 中编译 void toSendMemory2 toSendMemory 4 我不知道为什么 尽管我确信我这样做很愚蠢 P 当你添加N to a T 指针将增加sizeof T N bytes sizeof voi
  • Visual Studio 2013 C++ lambda 捕获参数包

    目前 Visual Studio 2013 update 2 不支持完整的 C 11 其中一项功能是捕获 lambda 中的参数包 有没有一种简单的方法可以解决这个问题 或者我是否必须放弃 Visual Studio 并使用兼容的编译器 例
  • IE7:如何让TD浮动?

    我想要一套 td s 在 IE7 中向左浮动 如果窗口太小 它们应该中断到下一行 CSS table width 100 td border 1px solid red tr f td width 500px float left HTML
  • 托管 Angular 2 应用程序

    我是新来的Angular 2 我认识楼主Angular 1 x在共享主机上 例如GoDaddy 但我不知道如何发布Angular 2应用程序 例如我有这个结构文件夹 angular2 quickstart app app component
  • 如何使用所有模型的通用 Trait 在 Laravel 中实现 eloquent 事件

    我在用拉拉维尔 5 4创建一个网络应用程序 我创建了一个特征来实现创建 更新 删除和恢复雄辩事件的事件 我创建了一个trait如下
  • 如何使用 AngularJS 更改一个 div 上的类,同时将鼠标悬停在另一个 div 上?

    我想使用 AngularJS 指令更改一个 div 的类 同时将鼠标悬停在另一个 div 上 这是我到目前为止所拥有的http jsfiddle net E8nM5 38 http jsfiddle net E8nM5 38 HMTL di
  • 当indexedDB被阻止时应用程序应该如何反应

    我在另一个地方被告知question https stackoverflow com questions 39997018关于检测阻止和解除阻止事件 阻止的打开 或删除 不会被取消 只是 被阻止 一旦解除阻止 打开 或删除 将继续 我想知道
  • Wcf 基本身份验证

    通过简单的测试 Wcf 服务使用基本身份验证时遇到一些问题 我遇到了一个例外 无法激活请求的服务 http qld tgower test Service svc 有关详细信息 请参阅 gt 服务器的诊断跟踪日志 在跟踪日志中它显示 在主机
  • WPF DataGrid实际ColumnHeaderHeight

    当我将 WPF DataGrid 的 ColumnHeaderHeight 设置为 Auto double NaN 时 如何获取列标题的实际呈现高度 我似乎无法在 DataGrid 类中找到该属性 您可以通过在视觉树中搜索来获取它DataG
  • 按照教程 AWS Elastic Beanstalk 的 Flask 教程时出现错误“Your requests.txt is invalid”

    我正在关注 AWS Elastic Beanstalk 的烧瓶教程 http docs aws amazon com elasticbeanstalk latest dg create deploy python flask html部署示
  • 用于确定测试成绩通过/失败的 MIPS 程序

    我正在编写一个 MiPS 程序 该程序将检查 15 个测试分数的列表 它将从终端输入 通过标准是 50 分 终端的输出将包括每个类别的分数以及通过和失败的学生人数 我应该使用输入提示和输出语句 请我需要一些帮助 只需要一些建议如何去做 ma
  • 禁用 GridView 列调整大小

    有什么方法可以在 WPF 中禁用 GridViewColumn 调整大小吗 我不想设置控件的样式 请参阅此链接 ListView 中的固定宽度列 无法调整大小的列 http blogs msdn com b atc avalon team
  • Spark 如何向工作线程发送闭包?

    当我编写 RDD 转换时 例如 val rdd sc parallelise 1 to 1000 rdd map x gt x 3 据我了解 关闭 x gt x 3 这只是一个 Function1 需要可序列化 并且我想我在某处读过编辑 它
  • 有没有办法在 CSS 中查询具有多个类的元素?

    如何查询同时具有两个类的元素 例如 div span class major minor Test span div 我想对同时具有 主要 和 次要 类的所有跨度进行样式设置 以下应该可以解决问题 span major minor colo
  • 添加黑条以创建 16x9 图像

    我的服务器上有一张jpg 我用 imagecreatefromjpeg imgPath 打开它 我想通过在顶部 底部或左侧 右侧添加黑条来使其成为 16x9 图像 思考background size contain background p
  • 使用 pandoc 从 Markdown 转换为 PDF 时设置双倍间距和行号

    我正在使用 markdown 和 pandoc 进行科学写作 我知道我可以使用以下命令更改最终 pdf 的边距 使用 pandoc 从 Markdown 转换为 PDF 时设置边距大小 https stackoverflow com que
  • Jackson @ResponseBody 上的内部服务器错误

    我只想将我的用户对象作为 JSON 返回 以供客户端的 ajax 调用使用 这在某一时刻是有效的 经过一些更新 即 将应用程序更改为部署到 在 Jetty 中 后 现在就不行了 我没有从代码中抛出异常 它返回得很好 但在尝试将对象转换为 J