Jackson @ResponseBody发生内部服务器错误 [英] Internal server error on Jackson @ResponseBody

查看:111
本文介绍了Jackson @ResponseBody发生内部服务器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这个工作在某一时刻,经过一些更新(即更改应用程序以部署到/在Jetty中),现在不是。



我没有从代码中抛出异常,它返回的很好,但似乎在尝试转换对象时在Jackson的根代码中爆炸到JSON。

就像我说过的,我没有发现异常,我的ajax调用只会说错误代码500,内部服务器错误。

  / *用户包含有关本网站用户的信息,该网站上下文中仅存在
* (没有名字,地址)。
* /
@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)
私人字符串名称;

@NotEmpty
@MinSkipEmpty(value = 4)
@MaxSkipEmpty(value = 40)
@Column(name =password,length = 40)
私人字符串密码;

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

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

@Column(name =last_login)
私人日期lastLogin;
$ b @ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name =USER_AUTHORITY)
@Column(name =authority)
private List<整数>当局;


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

公共列表<整数> getAuthorities(){
返回权限;
}

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

}

这是Person Entity



  @Entity(name =Person)
@Table(name =PERSON)
public class Person扩展AuditableEntity实现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)
私人字符串电子邮件;
$ b $ @DateTimeFormat(pattern =MM / dd / yyyy)
@NotNull(message =必填字段)
@Column(name =date)
私人日期生日;

@ManyToOne(fetch = FetchType.LAZY,cascade = {CascadeType.PERSIST})
@JoinColumn(name =location_id)
私人位置位置;

$ b 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;

$ b @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());
返回结果;

$ b @Override
public boolean equals(Object obj){
if(this == obj)
return true;
if(obj == null)
return false;
if(getClass()!= obj.getClass())
return false;
Person其他=(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;
返回true;
}

}






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

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name =id)
private长ID;

//人物/地点/物品的名称

@Column(name =name,length = 128)
字符串名称;

//街道地址,p.o. box,company name,c / o
@NotEmpty
@MaxSkipEmpty(value = 128)
@Column(name =line_1,length = 128)
String line1;

// apt。,suite,building,floor,entrance,等
@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)
字符串状态;

//邮政编码
@NotEmpty
@MaxSkipEmpty(值= 16)
@Column(name =zip,length = 16)
字符串拉链;

@Column(name =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;
尝试{
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();
返回用户;






  @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(用户用户){

Query query = entityManager.createQuery(new StringBuffer()
.append(从文档d中选择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);
列表<文档> 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;
}

}

ErrorExceptionResolver:

  @Component 
public class BWHandlerExceptionResolver extends SimpleMappingExceptionResolver implements InitializingBean {

public void afterPropertiesSet()throws Exception { b $ b属性props = new Properties();
props.put(Exception.class.getName(),error);
this.setExceptionMappings(道具);



解决方案

答案这是通过给它一个@Transactional注解来包装控制器方法。这解决了我的问题。


I just want to return my user object as JSON for use by an ajax call on the client-side.

This was working at one point, and after some updates (namely, changing the application to deploy to / in Jetty), now it's not.

I'm not throwing an exception from the code, it is returning just fine, but seems to blow up somewhere in the root code in Jackson when trying to convert the object to JSON.

Like I said, I'm not getting an exception, my ajax call just blows up saying error code "500, Internal Server Error".

/* 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;
}

}

This is the Person Entity

@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;
    }

}

ErrorExceptionResolver:

@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);

    }

解决方案

The answer to this was to wrap the controller method in a transaction by giving it the @Transactional annotation. That fixed my issue.

这篇关于Jackson @ResponseBody发生内部服务器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆