检测问号
我需要实现一个协议(protocol),用户可以在该协议(protocol)中提供附加到 URL 的问号,以便检索有关所提供资源的附加信息。我知道 URL 资源后面的问号表示查询参数。不幸的是,该协议(protocol)确实要求在 URL 末尾添加问号作为指示符。
实现
我使用 Jersey 实现了该服务。
@GET
@Path("{/service/")
@Produces(MediaType.TEXT_PLAIN)
public String resolve(@PathParam("uri") String fqn,
@PathParam("ark") String arkLabel,
@Context UriInfo ui, @Context HttpServletRequest hsr) {
// here i need to test of the url ends with ?
if (url.endsWith("?")) {
// to something
}
}
问题
我发现从 UriInfo
和 HttpServletRequest
提供的所有方法都会去掉最后一个问号(如果后面没有查询参数)。如何获取原始 URL,包括末尾的问号?
解决方案
根据@cy3er的回答我可以解决这个问题。下面的截图就可以解决这个问题。如果 URL 不包含任何查询,即 URL 上没有附加 ?
,则 getQueryString()
方法将返回 null。然后我可以假设如果字符串为空,则只有一个 ?
,因为查询为空。在第三个 caswe 中,我可以检查传递的唯一查询参数是否是一个 ?
,它对应于 URL 中的两个 ??
。
if (hsr.getQueryString() == null) {
this.logger.info("Normal link");
} else if (hsr.getQueryString().equals("")) {
this.logger.info("one ?");
} else if (hsr.getQueryString().equals("?")) {
this.logger.info("Two ??");
} else {
this.logger.info("None of the above");
}
最佳答案
使用HttpServletRequest
的getQueryString
方法,如果它为null,则没有任何问号。
请参阅documentation
关于java - 泽西 REST 服务 : Detect if URL ends with a questionmark,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27151757/