【问题标题】:How to open URL with anchors in Java?如何在 Java 中打开带有锚点的 URL?
【发布时间】:2023-03-25 05:18:01
【问题描述】:

我想为我的项目添加文档。通过单击 F1,我在某个位置打开文档(对于文档,我有 1 个文件(index.htm))。但是,我无法使用锚点打开 URL。我已经形成了正确的 URL,但是 .browse () 打开文档时没有锚(开头)。

public void openHtmlDocument() throws IOException, URISyntaxException {
     ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
     File file = new File(servletContext.getRealPath("/documentation/index.htm"));
     URL url = new URL(file.toURI().toURL(), "#_Toc502051959");
     Desktop.getDesktop().browse(url.toURI());
 }

我该如何解决这个问题?其他答案对我来说并不实际,因为用户使用 Windows 或 Linux。 形成的 URI:

file:/D:/app/wildfly-13.0.0.Final/standalone/tmp/vfs/deployment/deployment545477ea955f6f3d/mainUI-1.2.14.0.war-7f1f239336b4e258/documentation/index.htm#_Toc502051959

打开后我的浏览器网址:

【问题讨论】:

  • 请发布文本本身,而不是发布文本图像(例如该 URI)。
  • Thomas,根据您的评论更正了一个问题。
  • 可以添加浏览器地址栏的截图吗?您是否检查过任何重定向等?既然你写的是“一开始” - 你的意思是一旦浏览器打开就可以工作吗?
  • 在浏览器中添加了地址。不,我的意思是文档在第 1 行打开
  • 看来您正在使用 JSF。你见过这个page吗?

标签: java


【解决方案1】:

这真的很痛苦。 Desktop.browse 不适用于此处讨论的锚点: How to launch a file protocol URL with an anchor from Java? 该链接为 Windows 提供了可能的解决方法。

在 Linux 中,您可以通过执行以下命令打开 url:

Runtime.exec("open file:/D:/app/wildfly-13.0.0.Final/standalone/tmp/vfs/deployment/deployment545477ea955f6f3d/mainUI-1.2.14.0.war-7f1f239336b4e258/documentation/index.htm#_Toc502051959");

【讨论】:

  • 感谢您的解决方案,但这并没有解决我的问题
【解决方案2】:

我的问题的解决方案,如果突然有人遇到同样的问题:

    String menuNameNotBlanked = menuName == null ? "" : menuName.replace(" ","_");
    String formPathNotBlanked = formPath == null ? "" : formPath.replace(".xhtml","").replace("/","_");
    String helpPath = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getRealPath(HELP_FILE_PATH);

    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    URL contextURL = new URL(request.getScheme(),request.getServerName(),request.getServerPort(),request.getContextPath());
    URL helpURL = new URL(contextURL.toString()+ "/" + HELP_FILE_PATH + AddLeadString(menuNameNotBlanked+formPathNotBlanked,"#"));
    RequestContext.getCurrentInstance().execute("window.open('" + helpURL + "')");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    • 2019-02-15
    • 2015-11-08
    • 2011-10-22
    • 2015-07-12
    • 2019-11-21
    • 1970-01-01
    相关资源
    最近更新 更多