简体   繁体   中英

How to open URL with anchors in Java?

I would like to add documentation to my project. By clicking on F1, I open the documentation in a certain place (for documentation I have 1 file(index.htm)). However, I can not open the URL with anchor. I have formed the correct URL, but .browse () open the document without anchor(at the beginning).

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());
 }

How can I fix this? The rest of other answers did not actual for me, because users use Windows or Linux. Formed 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

My browser URL after opening:

*文件:/// d:/app/wildfly-13.0.0.Final/standalone/tmp/vfs/deployment/deploymentcbce740f6f42d6cf/mainUI-1.2.14.0.war-6c39ba4477e29f99/documentation/index.htm*

This is really a pain. Desktop.browse is not working with anchors as discussed here: How to launch a file protocol URL with an anchor from Java? The link gives possible workarounds for windows.

With Linux you may be able to open the url by executing this command:

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");

Solution for my problem, if suddenly someone faces the same problem:

    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 + "')");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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