使用:Java EE + JAX-RS(Apache Wink)+ WAS。
假设我有类Hello,路径"/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 :(得分:1)
将@Context
添加到方法调用或类中,并注入HttpServletRequest
或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());
答案 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 "";
}