![](/img/trans.png)
[英]how to fetch anotations values in writeTo method of MessageBodyWriter in jersey?
[英]How to retrieve resource method's Annoations in MessageBodyWriter in Jersey?
球衣 2.21。
我有一個像下面這樣的資源文件
……
@POST
@Path("/userReg")
@Produces("application/json;charset=UTF-8")
public JsonResp userReg(UserRegReq userRegReq) throws LoginNameExists {
HttpHeaderUtils.parseHeaders(userRegReq, headers);
//JsonResp is a custom java class.
JsonResp result = new JsonResp();
//will throw LoginNameExists
User user = userManager.register(userRegReq.getLoginName(), userRegReq.getPassword());
//success
result.setResult(0);
result.setData(user.getId);
return result;
}
……
為了將結果返回給客戶端,我實現了一個自定義 MessageBodyWriter,如下所示
@Produces("application/json")
public class MyRespWriter implements MessageBodyWriter<JsonResp> {
@Override
public boolean isWriteable(Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
return type == JsonResp.class;
}
@Override
public long getSize(JsonResp jsonResp, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) {
return 0;
}
@Override
public void writeTo(JsonResp jsonResp, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> multivaluedMap, OutputStream outputStream) throws IOException, WebApplicationException {
//if these no exception in userReg(),
//the parameter annotations contains the annotations
//such as POST, Path, Produces;
//but if there is an exception in userReg(),
//the parameter annotations contains none of POST, Path, Produces;
//So, is there any way to retrieve the original annotations all along?
//JsonUtils is a custom java class.
String data = JsonUtils.toJsonString(jsonResp);
Writer osWriter = new OutputStreamWriter(outputStream, "UTF-8");
osWriter.write(data);
osWriter.flush();
}
}
為了處理異常,我實現了一個這樣的 ExceptionMapper:
public class MyExceptionMapper implements ExceptionMapper<Exception> {
public Response toResponse(Exception e) {
JsonResp result = new JsonResp();
//error
result.setResult(-1);
result.setErrMsg("System error.");
return Response.ok(result, MediaType.APPLICATION_JSON_TYPE).status(Response.Status.OK).build();
}
}
現在,如果一切正常,並沒有異常,代碼執行路由器userReg() -> MyRespWriter.writeTo()
的參數“注釋” MyRespWriter.writeTo()
包含方法的正確注釋userReg()
如POST
、 Path
、 Produces
。
但是如果userReg()
拋出異常,則代碼執行路由是userReg() -> MyExceptionMapper.toResponse() -> MyRespWriter.writeTo()
,方法MyRespWriter.writeTo()
的參數“annotations”沒有方法的注釋userReg()
。
我想知道,有什么方法可以讓MyRespWriter.writeTo()
檢索原始注釋?
您可以注入ResourceInfo
,然后使用ri.getResourceMethod()
獲取Method
,然后調用method.getAnnotations()
以獲取注釋。
public class MyRespWriter implements MessageBodyWriter<JsonResp> {
@Context
ResourceInfo ri;
...
Annotations[] annos = ri.getResourceMethod().getAnnotations();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.