Gwt RequestBuilder using PostData:
hi every one, today we will be working on RequestBuilder. as we have seen before as how to make a call to server [java servlet] . today we will do the same thing but we will send out own data as a part of request and access it on the server side. so lets start creating the class, i will use the old servlet as in the previous blogs . to return the reverse of the string that is sent from client side. the servlet looks like this ,
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/xml");
String StringToServer=req.getParameter("string");
System.out.println(StringToServer);
StringBuffer buffer=new StringBuffer(StringToServer);
String s=new String(buffer.reverse());
resp.getWriter().print(s);
}
}
now on the Client side in OnModuleLoad() ,
as everyone know that we can send our data to server in the url it self , but in the case of post , the url may not seen . so for this case we will be writing our own data and send it as a string . for this we will be using URL classs available in gwt .I want to send the value for a parameter "string" that can be accessed on the server side i.e in servlet
StringBuffer postData=new StringBuffer();
postData.append(URL.encode("string")).append("=").append(URL.encode(toServer));
and i have added a parameter called "string" and provided its values i.e toServer.
i will send this postData as a first argument in RequestBuilder.sendRequest() method .
lets look at the complete code as how it looks
private String StringToServer;
private HorizontalPanel hPanel;
private String url_host="";
private static final int STATUS_CODE_OK = 200;
private RequestBuilder builder;
private StringBuffer postData ;
//OnModuleLoad()
public void onModuleLoad() {
postData = new StringBuffer();
url_host=GWT.getModuleBaseURL()+"/server/ServletCallback";
builder=new RequestBuilder(RequestBuilder.POST,url_host);
builder.setHeader("Content-type", "application/x-www-form-urlencoded");
hPanel=new HorizontalPanel();
hPanel.add(new TextBox());
hPanel.add(new Button("Get String Reverse",new ClickListener() {
public void onClick(Widget sender) {
try {
String toServer=((TextBox)hPanel.getWidget(hPanel.getWidgetCount()-2)).getText();
postData.append(URL.encode("string")).append("=").append(URL.encode(toServer));
builder.sendRequest(postData.toString(), new RequestCallback() {
public void onError(Request request, Throwable exception) {
Window.alert("on error");
}
public void onResponseReceived(Request request,
Response response) {
Window.alert(response.getText());
}
});
}catch(Exception e) {
e.printStackTrace();
}
}//onClick
}));
RootPanel.get().add(hPanel);
}
}
Thank u,
jagadesh
No comments :
Post a Comment