gpt4 book ai didi

java - 如何在 Jersey 的 MessageBodyWriter 中检索资源方法注释?

转载 作者:行者123 更新时间:2023-11-30 10:52:15 25 4
gpt4 key购买 nike

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()的参数“annotations” )包含userReg()方法的正确注解,如POSTPathProduces .

但是如果userReg()抛出异常,代码执行路由是userReg() -> MyExceptionMapper.toResponse() -> MyRespWriter.writeTo(),参数方法 MyRespWriter.writeTo() 的“注释”没有方法 userReg() 的注释。

我想知道,MyRespWriter.writeTo()有什么方法可以一直检索原始注释吗?

最佳答案

你可以注入(inject)ResourceInfo ,然后通过ri.getResourceMethod()获取Method,然后调用method.getAnnotations()获取注解。

public class MyRespWriter implements MessageBodyWriter<JsonResp> {

@Context
ResourceInfo ri;

...

Annotations[] annos = ri.getResourceMethod().getAnnotations();

关于java - 如何在 Jersey 的 MessageBodyWriter 中检索资源方法注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34415895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com