In this blog we will see how can we retrive json data from a servlet by making a call to server by using RequestBuilder.
Here is the servlet on the server side,
public class MySampleServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
JSONObject json = new JSONObject();
json.put("city", "Mumbai");
json.put("country", "India");
resp.setContentType("text/x-json");
resp.getWriter().print(json.toString());
}
}
And in the onModuleLoad () , we have
public class Application implements EntryPoint {
private String url_host="";
private static final int STATUS_CODE_OK = 200;
private RequestBuilder builder;
private Button myButton;
public void onModuleLoad() {
url_host=GWT.getModuleBaseURL()+"/server/ServletCallback";
builder=new RequestBuilder(RequestBuilder.POST,url_host);
builder.setHeader("Content-type", "application/x-www-form-urlencoded");
myButton=new Button("Click Me",new ClickListener(){
public void onClick(Widget sender) {
try{
builder.sendRequest(null,new RequestCallback(){
public void onError(Request request, Throwable exception) {
}
public void onResponseReceived(Request request,
Response response) {
Window.alert(response.getText());
}
});
}catch(Exception e){
e.printStackTrace();
}
}
});
RootPanel.get().add(myButton);
}//Close of OnmoduleLoad()
}
donot forget to add an servlet entry into the .gwt.xml file .
<servlet path="/server/ServletCallback" class="com.example.server.MySampleServlet"/>
No comments :
Post a Comment