JavaEE如何从类声明它获取api路径

时间:2014-11-06 09:23:33

标签: rest java-ee jax-rs apache-wink

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

假设我有类Hello,路径"/hello"

声明的Rest API
@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)中的示例,它可以以某种方式获取它,找不到它的来源。

2 个答案:

答案 0 :(得分:1)

@Context添加到方法调用或类中,并注入HttpServletRequestUriInfo,无论哪种更有用,如下所示:

// 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());

答案 1 :(得分: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 "";
}