Search code examples
javaprimefacesjsf-2

Desktop and URI Producing Character Artifact


I have a Primefaces Commandlink that is giving me an artifact at the end of my mailto address. I am not sure where the '#' is coming from.

enter image description here

Here is the front-end code.

<p:commandLink value="Mail Video Link" action="#{requestBean.requestUtility.informationRequestLink()}" />     

Here is the back-end action code.

    public void informationRequestLink() {
    String subject = "Video Link";
    String cc = "[email protected],[email protected]";
    String requestLink = "https://www.youtube.com/watch?v=SjeS6gtPq8E";
    String body
            = "Here is the link.\n"
            + requestLink + "\n\n"
            + "Watch at your leisure.";

    try {
        Desktop desktop = Desktop.getDesktop();

        String mailURIString = String.format("?subject=%s&cc=%s&body=%s",
            subject, cc, body);
        URI mailURI = new URI("mailto", "[email protected]", mailURIString);

        desktop.mail(mailURI);
    } catch (IOException | URISyntaxException e) {
        e.printStackTrace();
    }   
}

[EDIT]

I can get rid of the '#' but then I get UTF-8 encoded spaces '+'.

enter image description here

        String subject = "Video Link";
    String cc = "[email protected],[email protected]";
    String requestLink = "https://www.youtube.com/watch?v=SjeS6gtPq8E";
    String body
            = "Here is the link.\n"
            + requestLink + "\n\n"
            + "Watch at your leisure.";

    try {
        Desktop desktop = Desktop.getDesktop();

        String mailURIString = String.format("mailto:%s?subject=%s&cc=%s&body=%s",
                "[email protected]", subject.replaceAll(" ", "%20"), cc, URLEncoder.encode(body, "UTF-8"));
        URI mailURI = URI.create(mailURIString);

        desktop.mail(mailURI);
    } catch (Exception e) {
        e.printStackTrace();
    }   

Solution

  • The hash-character is appended by the constructor you're using. Have a look at the JavaDoc:

    public URI(String scheme, String ssp, String fragment) throws URISyntaxException

    [...]

    Finally, if a fragment is given then a hash character ('#') is appended to the string, followed by the fragment. Any character that is not a legal URI character is quoted.

    You should use the appropriate constructor of URI; refer to the documentation. To me, it seems your third argument is more a query than a fragment.