javajqueryjsonajaxjava-server

Ajax Follow Java Serverlet Redirect


I'm making a certain ajax request to a java serverlet in the following manner :

var request = $.ajax({
    type: "POST",
    url: MY_SERVERLET_URL,
    data: MY_DATA,
    dataType: 'json',
});

request.done(function(msg) {
    if (msg.hasOwnProperty("status")) {
        var jsonObject = msg["status"].toString();
        if (jsonObject == "success") {
            // GET RELEVANT URL AND DATA FROM JSON OBJECT AND REDIRECT TO
            // THE URL WITH DATA ATTACHED FROM JAVASCRIPT
        }
        else {
            // ERROR
        }
    }
    else {
       // ERROR
    }
});

request.fail(function(jqXHR, textStatus) {
    alert("Error : " + textStatus);
});

What I have Done

Currently the Java serverlet completes its work and returns a certain URL and a set of data inside a JSON Object to the ajax request, where the ajax request in turn will parse that data and make a certain POST request to the specified url.

What I Want To Do

I want to do this without returning the data to the client side, meaning to make the request from the Java serverlet directly to the the url but the ajax request from the client side should also follow that request. (The user should be redirected to the specified URL)


Solution

  • I've understand that you want to make an internal POST request in your servlet and forward or redirect the client according to what you've received.

    activity

    Client side

    A simple form could be enough. Submit with XHR or not.

    HTML

    <form action="/yourServlet" method="POST">
        <input type="hidden" name="data" value="value" />
    </form>
    

    Server side

    Encode parameters to queryString

    public String getEncodedQueryString(Map<String, String> parameters) {
        StringBuilder queryStringBuilder = new StringBuilder("?");
        parameters.entrySet().stream().forEach(e -> {
            queryStringBuilder.append(e.getKey());
            queryStringBuilder.append("=");
            try {
                queryStringBuilder.append(
                    URLEncoder.encode(e.getValue() == null ? "" : e.getValue().toString(), StandardCharsets.UTF_8.name())
                );
            }
            catch (UnsupportedEncodingException e1) {
                queryStringBuilder.append("");
            }
            queryStringBuilder.append("&");
        });
        return queryStringBuilder.toString().substring(0, queryStringBuilder.toString().length()-1);
    }
    

    Post your data to some URL inside your servlet

    (maybe the URL is one of your parameters as well from the POST?)

    URLConnection connection = new URL(url).openConnection();
    connection.setDoOutput(true); // POST
    connection.setRequestProperty("Accept-Charset", "UTF-8");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    try (OutputStream output = connection.getOutputStream()) {
        output.write(getEncodedQueryString(request.getParameterMap()).getBytes(StandardCharsets.UTF_8));
    }
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String inputLine;
    while ((inputLine = in.readLine()) != null) { sb.append(inputLine); }
    in.close();
    

    Write your data

    request.setAttribute("param", sb.toString());
    /*
        return ResponseBody<> or String or whatever according
        to your servlet container like you're doing usually
    */
    

    Hope this helps.