Search code examples
urluridecodeencode

URL encoding in java and decoding in javascript


I have an URL to encode on my java serveur and then to decode with javascript. I try to retrieve a String I send in param with java. It is an error message from a form validation function.

I do it like that (server side. Worker.doValidateForm() return a String) :

response.sendRedirect(URLEncoder.encode("form.html?" + Worker.doValidateForm(), "ISO-8859-1"));

Then, in my javascript, I do that :

function retrieveParam() {
    var error = window.location.search;

    decodeURIComponent(error);
    if(error)
        alert(error);
}

Of course it doesn't work. Not the same encoding I guess.

So my question is : which method can I use in Java to be able to decode my URL with javascript ?


Solution

  • It's ok ! I have found a solution.

    Server side with Java :

    URI uri = null;
    try {
        uri = new URI("http", "localhost:8080", "/PrizeWheel/form.html", Worker.doValidateForm(), null);
    } catch (URISyntaxException e) {
        this.log.error("class Worker / method doPost:", e); // Just writing the error in my log file
    }
    String url = uri.toASCIIString();
    response.sendRedirect(url);
    

    And in the Javascript (function called in the onload of the redirected page) :

    function retrieveParam() {
        var error = decodeURI(window.location.search).substring(1);
    
        if(error)
            alert(error);
    }