此代码用于访问 uriInfo:
@Path("/testing")
public class Testing {
@javax.ws.rs.core.Context UriInfo uriInfo;
@POST
@Path("/test2")
@Produces(MediaType.TEXT_PLAIN)
public Response test2(
@FormParam("sessionId") String sessionId ) {
String currentUserId = Utils.setup(sessionId);
String accessPath = uriInfo.getAbsolutePath().toASCIIString();
System.out.println("The client used this URI to reach this resource method: " + uriInfo.getAbsolutePath().toASCIIString());
// Utils.test3("print this");
return Response.ok("Test 2 ended").build();
}
当我尝试访问被调用方法 Utils.test3("print this"); 中的 uriInfo 时这里:
public class Utils {
@javax.ws.rs.core.Context static UriInfo uriInfo;
public static String setup(String sessionId) {
if (!com.retailapppartners.Utils.validSession(sessionId)) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
String currentUserId = com.retailapppartners.Utils.getUserFromSession(sessionId);
MDC.put("user-id", currentUserId);
return currentUserId;
}
public static void test3(String message) {
System.out.println(message);
String path = uriInfo.getPath();
// System.out.println("The client used this URI: " + uriInfo.getAbsolutePath().toASCIIString());
return;
}
此操作因空指针异常而失败。我想查看被调用方法中的路径 uri,以确认我的 utils 被调用方法中所有方法的安全性。我已经在高低之间搜索过这样的例子。谢谢
最佳答案
使用@Context注释将UriInfo实例注入(inject)到资源类的字段变量或方法参数中
例如#1
public String find(@Context UriInfo uri){}
例如#2
public class RESTResource{
@Context
private UriInfo uri;
}
关于java - 在调用的方法中访问 iriInfo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28951536/