-1

使用:Java EE + JAX-RS (Apache Wink) + WAS。

假设我有类 Hello, path 声明的 Rest API"/hello"

@Path("/hello")
public class Hello{

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response sayHello() {
        Map<String, String> myMap = new LinkedHashMap<String, String>();
        myMap.put("firstName", "To");
        myMap.put("lastName", "Kra");
        myMap.put("message", "Hello World!");
        Gson gson = new Gson(); 
        String json = gson.toJson(myMap);       
        return Response.status(200).entity(json).build();
   }
}

如何在Hello.class不使用反射的情况下获得该路径?我可以在javax.ws.rs.core.UriBuilder方法path(Class clazz)中看到可以以某种方式获取它的示例,但找不到它的来源。

4

2 回答 2

1

添加@Context到方法调用或类并注入HttpServletRequestor UriInfo,任何更有用的东西,如下所示:

// as class fields
@Context
private HttpServletRequest request;

@Context
private UriInfo uriInfo;
...

// or as param in method
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response sayHello(@Context UriInfo uriInfo) {
....

System.out.println(request.getRequestURI());
System.out.println("uri: " + uriInfo.getPath());
System.out.println("uri: " + uriInfo.getBaseUri());
于 2014-11-06T10:15:57.087 回答
0

反射解决方案:

/**
 * Gets rest api path from its resource class
 * @param apiClazz
 * @return String rest api path
 */
public static String getRestApiPath(Class<?> apiClazz){
    Annotation[] annotations = apiClazz.getAnnotations();
    for(Annotation annotation : annotations){
        if(annotation instanceof Path){
            Path pathAnnotation = (Path) annotation;
            return pathAnnotation.value();
        }
    }
    return "";
}
于 2014-12-11T09:32:44.983 回答