-1

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)

Paul
  • 1,410
  • 1
  • 14
  • 30
Elinoter99
  • 599
  • 1
  • 7
  • 22
  • Possible duplicate of [pass post data with window.location.href](https://stackoverflow.com/questions/2367979/pass-post-data-with-window-location-href). – Paul Jun 13 '19 at 09:02
  • @paul.F-G No, in my case i want to send the POST request from Java itself. – Elinoter99 Jun 13 '19 at 09:15
  • So you want to get additional data in your servlet from a POST request and then send a redirect or forward to the client with this data? What servlet container are you using? – Paul Jun 13 '19 at 09:17
  • A basic web container, but its running independently. Meaning the JS (client side) is hosted in a different server and the Java Serverlet hosted in another server – Elinoter99 Jun 13 '19 at 09:48

1 Answers1

1

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.

Paul
  • 1,410
  • 1
  • 14
  • 30