2014-11-06 56 views
-1

使用:Java EE + JAX-RS(Apache Wink)+ WAS。JavaEE如何从类声明它的API路径

让说,我有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)中看到例子,它可以以某种方式得到它,找不到它的来源。

+0

请告诉我您的问题@AndrewBarber ? – 2015-02-04 09:12:34

回答

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 ""; 
} 
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()); 
+0

这不是我在我的问题中的意思。但thx – 2014-12-11 09:33:48

+0

@ToKra那么这个'UriBuilder.fromResource(Hello.class).build()。toString()'是如何更多你在找什么? – Gas 2014-12-11 14:10:34