我目前正在开发REST-API。我正在使用泽西岛。
之前我编写了几个接口,它们都运行良好。现在,我完全以相同的方式(在我看来)这样做,但它不知何故不起作用。
问题是userGet()没有记录任何错误(TRY-CATCH内部没有发生错误),并且SEEMS就像方法执行成功一样。但客户端仅收到" 500内部服务器错误" - 响应。
您是否知道如何找出错误发生的位置?或者你已经知道我做错了什么?
这是我应该由API返回的类:
package myproject.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class UserModel {
@XmlElement(name = "id")
private long id = -1;
@XmlElement(name = "strUsername")
private String username = null;
@XmlTransient
private String encryptedPassword = null;
@XmlElement(name = "Consultant", nillable = true)
private Consultant consultant = null;
public UserModel(long id, String username, String encPw, Consultant co) {
this.id = id;
this.username = username;
this.encryptedPassword = encPw;
this.consultant = co;
}
public static UserModel fromUser(User u) {
return new UserModel(u.getId(), u.getName(), u.getEncryptedPassword(), u.getConsultant());
}
public User toUser() {
return User.fromUserModel(this);
}
public long getId() {
return id;
}
public String getUsername() {
return username;
}
public String getEncryptedPassword() {
return encryptedPassword;
}
public Consultant getConsultant() {
return consultant;
}
public String toString() {
return "id=" + id + ";username=" + username + ";encPw=" + encryptedPassword;
}
}
我的REST-API:
package myproject.rest;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import myproject.User;
import myproject.UserModel;
import myproject.DBUtil;
import myproject.SecurityUtil;
@Path("/app/user")
public class HandlerUser extends RestEndpoint {
private static Logger log = Logger.getLogger(HandlerUser.class);
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response userGet() {
Connection con = null;
try {
con = DBUtil.getDBConnection();
//SecurityUtil.checkRight(request);
log.info("Collect all Users");
List<UserModel> usermodels = new ArrayList<UserModel>();
Iterator<User> it = User.getAll(con).iterator();
while(it.hasNext()) {
usermodels.add(it.next().toUserModel());
}
GenericEntity<List<UserModel>> entity = new GenericEntity<List<UserModel>>(usermodels) {};
return Response.ok().entity(entity).build();
}
catch(Exception e) {
log.error("An error occured: " + e.toString());
return Response.status(401).entity(e.toString()).build();
}
finally {
DBUtil.close(null, null, con);
}
}
}
编辑: User.toUserModel()将User-Object转换为UserModel-Object(工作正常)