[英]How I return HTTP 404 JSON/XML response in JAX-RS (Jersey) on Tomcat?
我有以下代碼:
@Path("/users/{id}")
public class UserResource {
@Autowired
private UserDao userDao;
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public User getUser(@PathParam("id") int id) {
User user = userDao.getUserById(id);
if (user == null) {
throw new NotFoundException();
}
return user;
}
如果我通過“ Accept: application/json
”請求不存在的用戶(例如/users/1234
,則此代碼返回HTTP 404
響應,就像人們期望的那樣,但將Content-Type
集返回到text/html
和html的正文消息。 注釋@Produces
被忽略。
這是代碼問題還是配置問題?
您的@Produces
注釋被忽略,因為jax-rs運行時使用預定義的(默認) ExceptionMapper
處理未捕獲的ExceptionMapper
如果要在特定異常的情況下自定義返回的消息,您可以創建自己的ExceptionMapper
來處理它。 在您的情況下,您需要一個處理NotFoundException
異常並查詢所請求的響應類型的“accept”標頭:
@Provider
public class NotFoundExceptionHandler implements ExceptionMapper<NotFoundException>{
@Context
private HttpHeaders headers;
public Response toResponse(NotFoundException ex){
return Response.status(404).entity(yourMessage).type( getAcceptType()).build();
}
private String getAcceptType(){
List<MediaType> accepts = headers.getAcceptableMediaTypes();
if (accepts!=null && accepts.size() > 0) {
//choose one
}else {
//return a default one like Application/json
}
}
}
您可以使用響應返回。 示例如下:
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response get(@PathParam("id") Long id) {
ExampleEntity exampleEntity = getExampleEntityById(id);
if (exampleEntity != null) {
return Response.ok(exampleEntity).build();
}
return Response.status(Status.NOT_FOUND).build();
}
您的服務器返回404,因為您希望以下列形式傳遞內容
/users/{id}
但是你把它傳遞給了
/users/user/{id}
哪個資源根本不存在
嘗試訪問資源/users/1234
編輯:
創建一個類似的
class RestResponse<T>{
private String status;
private String message;
private List<T> objectList;
//gettrs and setters
}
現在,如果您想要響應User
您可以按如下方式創建它
RestResponse<User> resp = new RestResponse<User>();
resp.setStatus("400");
resp.setMessage("User does not exist");
和你的休息方法的簽名將如下
public RestResponse<User> getUser(@PathParam("id") int id)
如果成功響應你可以設置像
RestResponse<User> resp = new RestResponse<User>();
List<User> userList = new ArrayList<User>();
userList.add(user);//the user object you want to return
resp.setStatus("200");
resp.setMessage("User exist");
resp.setObjectList(userList);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.