MaNn
MaNn

Reputation: 785

GWT- POST object/json and go to another page

I referred this link : How to post data and redirect to another page using GWT?

I can use formpanel but I am stuck somewhere ,please help .

This is my code :

HashMap<String, String> map = new HashMap<String, String>();
map.add(...some information....); //want to send this map in POST

I want to send the map using POST and also I want to go to another page.

I can use this code (answered in How to post data and redirect to another page using GWT?):

 FormPanel form = new FormPanel("_self");
form.setMethod(FormPanel.METHOD_GET);

Hidden params0 = new Hidden("param1", "value1");
Hidden params1 = new Hidden("param1", "value2");
Hidden params2 = new Hidden("param2", "value3");

FlowPanel panel = new FlowPanel();
panel.add(params0);
panel.add(params1);
panel.add(params2);

form.add(panel);

form.setAction(GWT.getModuleBaseURL() + "../test");
RootPanel.get().add(form);
form.submit();

But how do I send already created map along with POST ?

At server side :

 @RequestMapping(value = "/test",method = RequestMethod.POST)
 @ResponseBody
 public String test(@RequestBody final HashMap<String, String> map,HttpSession session)
{
    //use the map
    return another-page.jsp
}

Upvotes: 0

Views: 1262

Answers (1)

thepun599
thepun599

Reputation: 150

Probably better to send data via RPC or AJAX and redirect to another page by Location.assign() or Location.replace(). If you expect the server to provide dynamic URL to redirect you can send it as a response for the RPC or AJAX request. In current example AJAX request is used:

// map is your existing map object
JSONObject data = new JSONObject();
for (String key : map.keySet()) {
    data.put(key, new JSONString(map.get(key)));
}

RequestBuilder request = new RequestBuilder(RequestBuilder.GET, "<URL>");
request.setRequestData(data.toString());
request.setCallback(new RequestCallback() {
    @Override
    public void onResponseReceived(Request request, Response response) {
        String url = response.getText();

        // url to redirect
        Window.Location.assign(url);
    }

    @Override
    public void onError(Request request, Throwable exception) {
        // handle error
    }
});

request.send();

Or you can serialize map to String and pass it as hidden field of a POST request.

Client code:

String buffer = Streamer.get().toString(map);

FlowPanel panel = new FlowPanel();
panel.add(new Hidden("map", buffer));

FormPanel form = new FormPanel("_self");
form.setMethod(FormPanel.METHOD_POST);
form.setAction(<URL>);
form.add(panel);
RootPanel.get().add(form);

form.submit();

Server code:

 @RequestMapping(value = <URL>,method = RequestMethod.POST)
 @ResponseBody
 public String test(@RequestBody String mapString,HttpSession session)
{
    Map<String, String> map = (Map<String, String>) Streamer.get().fromString(mapString);

    // use the map
    return another-page.jsp
}

Upvotes: 1

Related Questions