简体   繁体   English

如何从Java中的URL在主题标签后获取值

[英]How can I get value after hashtag from URL in Java

I have a URL and I want to print in my graphical user interface the ID value after the hashtag. 我有一个URL,我想在图形用户界面中的井号后面打印ID值。 For example, we have www.site.com/index.php#hello and I want to print hello value on a label in my GUI. 例如,我们有www.site.com/index.php#hello ,我想在GUI的标签上打印hello值。

How can I do this using Java in Netbeans? 如何在Netbeans中使用Java做到这一点?

Use the String.split() Method. 使用String.split()方法。

public static String getId(string url) {

    return url.split("#")[1];

}

String.split() returns an array of Strings that are delimited, or "Split," by the value you pass to it, or in this case # . String.split()返回一个字符串数组,该字符串数组由您传递给它的值(或#分隔。

Because you want only the string after the # , you can just use the second item in the array that it returns by adding [1] to the end of it. 因为只需要#之后的字符串,所以只需在其返回的数组中添加[1]就可以使用它返回的数组中的第二项。

For more on String.split() go to Tutorials Point . 有关String.split()更多信息,请转到Tutorials Point

By the way, the part of the URL you are referencing is the Element ID. 顺便说一句,您所引用的URL的一部分是元素ID。 It is used to jump to an Element on a webpage. 它用于跳转到网页上的元素。

Simple solution is getRef() in URL class: 简单的解决方案是URL类中的getRef()

URL url = new URL("http://www.anyhost.com/index.php#hello");
jLabel.setText(url.getRef());

EDIT: According to @Henry comment: 编辑:根据@亨利评论:

I would recommend to use the java.net.URI as it also deals with encoding. 我建议使用java.net.URI,因为它也处理编码。 The Javadocs say: "Note, the URI class does perform escaping of its component fields in certain circumstances. The recommended way to manage the encoding and decoding of URLs is to use URI, and to convert between these two classes using toURI() and URI.toURL()." Javadocs说:“请注意,URI类在某些情况下确实对其组件字段进行转义。建议的管理URL编码和解码的方法是使用URI,并使用toURI()和URI在这两个类之间进行转换。 .toURL()。”

and this comment: 这个评论:

Why not just doing uri.getFragment() 为什么不只是做uri.getFragment()

URI uri = new URI("http://www.anyhost.com/index.php#hello");
jLabel.setText(uri.getFragment());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM