I am new to web development. in GWT it uses its own set of RPC to call server side methods from the client. Now my question is that when we are doing development using plain html/css we can call a php script to b executed. So when we are designing using GWT can it call a Java program sitting on the server and if yes how does it call it? ALso apart from RestyGWT how can we use RESTful WS via GWT on the client side to call the java programs sitting on the server. Thanking you in anticipation.
Expose a URL to call your Java app functionality and use GWT's RequestBuilder.
private static String GET_SERVER_URL(String parameters) {
// make up your Java url here along with any parameters
...
return url;
}
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET,
GET_SERVER_URL(parameters));
try {
builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable caught) {}
public void onReponseReceived(Request request, Response response) {}
} catch (RequestException e) {}
}
Related
Normally, when we use HTTP requests, we have a specific set of methods/callbacks that would be called when the request succeeds/fails. Each connection request could have its own callback methods, which made structuring of code very easy.
So now that I am trying out Socket.io for a new project, I got all confused. For instance, you emit a message into the socket connection and you're done. no callbacks there. There is no easy way I can know if that actually succeeded or not I've managed to simulate a callback by writing this method:
public void emitRequest(final String event, JSONObject data, final emitResponseListener pListener)
{
mSocket.on(event+"_resp", new Listener() {
#Override
public void call(final Object... args) {
((Activity)c).runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
if (pListener!=null)
{
pListener.onResponseRecieved(data);
}
}
});
}
});
mSocket.emit(event,data);
}
This method listens for a event_resp message from the server after emitting an event. But thats as far as I've got. I have no clue as to how to handle errors for specific emits, so as to update the UI or inform the user .etc.
Sure, there are callback events for the Socket but those are impossible to wire up into the apps flow.
So does anybody know a way to achieve this? I searched a lot but couldn't find anything. I'm using Java Client but generalized answers for any client API are welcome.
You have to change your view - instead of callbacks think about events, and base your design accordingly.
When you make a request to the socket server, generate a unique token. Send the token to the server and have the server send it back with the request response. Using the token you can register a callback that will fire for event matching the request response event and this token.
This way you can execute the calls one after another.
To Cover cases where the server did not return a response, we use timeouts of 30 seconds. About 99.9% of the times we didn't get a response happened due to socket disconnection, so the socket error callback handled that after successful reconnection, without reaching the timeout.
I would like to know how to create a REST webservice that posts multipart request to upload the file without using third party libraries like Jersey or Spring.
Thanks.
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Path("/uploadfile")
void uploadFile(#Context HttpServletRequest request, #Multipart(value = "file", type = MediaType.APPLICATION_OCTET_STREAM)Attachment file);
I have an REST server as backend, it provides a set of services, also, it uses basic authentication method for access.
Now I need to create an GWT frontend,so, I need to perform http calls to the REST backend from the GWT frontend
After some research I found the HttpBuilder to handle http requests to the backend, but it seem to be a pain when trying to perform cross-site requests, and also it comes with some restricions related with Safari browser.
Then I found this https://developers.google.com/web-toolkit/doc/latest/tutorial/Xsite article, where it talks about an "Proxy on your own server", so it looks to be the solution I was looking for, but I did not find more information, or an example. It says that I could create server-side code to download the data from remote server (backend), so, should I create a http client like the apache client on server-side code, and implement a set of services that use it to make request to the backend?, if yes, how to handle the user authentication and the session? if not, give me a light please.
Thanks
it seem to be a pain when trying to perform cross-site requests,
Actually you can make Cross Site Requests from GWT RequestBuilder if we can set in Servlet Response Header
Response.setHeader("Access-Control-Allow-Origin","http://yourrestserviceur.com/url");
should I create a http client like the apache client on server-side code, and implement
a set of services that use it to make request to the backend?
No, it is not required. use RequestBuilder
RequestBuilder Example:
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
displayError("Couldn't retrieve JSON");
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
updateTable(asArrayOfStockData(response.getText()));
} else {
displayError("Couldn't retrieve JSON (" + response.getStatusText()
+ ")");
}
}
});
} catch (RequestException e) {
displayError("Couldn't retrieve JSON");
}
What is difference between a navigation in JSF
FacesContext context = FacesContext.getCurrentInstance();
context.getApplication().getNavigationHandler().handleNavigation(context, null, url);
and a redirect
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.sendRedirect(url);
and how to decide when to use what?
The issue with navigation is that page URL does not change unless faces-redirect=true is added to the query string of the navigation URL. However, in my case appending faces-redirect=true throws error if I want to redirect to a non-JSF page like a plain HTML page.
And another option is as BalusC suggested at JSF 2.0 redirect error
First of all, the term "redirect" is in web development world the action of sending the client an empty HTTP response with just a Location header with therein the new URL on which the client has to send a brand new GET request. So basically:
Client sends a HTTP request to somepage.xhtml.
Server sends a HTTP response back with Location: newpage.xhtml header
Client sends a HTTP request to newpage.xhtml (this get reflected in browser address bar!)
Server sends a HTTP response back with content of newpage.xhtml.
You can track it with the webbrowser's builtin/addon developer toolset. Press F12 in Chrome/IE9/Firebug and check the "Network" section to see it.
The JSF navigationhandler doesn't send a redirect. Instead, it uses the content of the target page as HTTP response.
Client sends a HTTP request to somepage.xhtml.
Server sends a HTTP response back with content of newpage.xhtml.
However as the original HTTP request was to somepage.xhtml, the URL in browser address bar remains unchanged. If you are familiar with the basic Servlet API, then you should understand that this has the same effect as RequestDispatcher#forward().
As to whether pulling the HttpServletResponse from under the JSF hoods and calling sendRedirect() on it is the proper usage; no, that isn't the proper usage. Your server logs will get cluttered with IllegalStateExceptions because this way you aren't telling JSF that you've already taken over the control of the response handling and thus JSF shouldn't do its default response handling job. You should in fact be executing FacesContext#responseComplete() afterwards.
Also, everytime whenever you need to import something from javax.servlet.* package in a JSF artifact like a managed bean, you should absolutely stop writing code and think twice if you're really doing things the right way and ask yourself if there isn't already a "standard JSF way" for whatever you're trying to achieve and/or if the task really belongs in a JSF managed bean (there are namely some cases wherein a simple servlet filter would have been a better place).
The proper way of performing a redirect in JSF is using faces-redirect=true query string in the action outcome:
public String submit() {
// ...
return "/newpage.xhtml?faces-redirect=true";
}
Or using ExternalContext#redirect() when you're not inside an action method such as an ajax or prerender listener method:
public void listener() throws IOException {
// ...
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.redirect(ec.getRequestContextPath() + "/newpage.xhtml");
}
(yes, you do not need to put a try-catch around it on IOException, just let the exception go through throws, the servletcontainer will handle it)
Or using NavigationHandler#handleNavigation() in specific cases if you're using XML navigation cases and/or a custom navigation handler with some builtin listener:
public void listener() {
// ...
FacesContext fc = FacesContext.getCurrentInstance();
NavigationHandler nh = fc.getApplication().getNavigationHandler();
nh.handleNavigation(fc, null, "/newpage.xhtml?faces-redirect=true");
}
As to why the navigation handler fails for "plain HTML" files, that is simply because the navigation handler can process JSF views only, not other files. You should be using ExternalContext#redirect() then.
See also:
How to navigate in JSF? How to make URL reflect current page (and not previous one)
When should I use h:outputLink instead of h:commandLink?
I don't know who to do this in gwt, I remember that I can define this in web.xml but I'm not sure about it.
Thanks
If you're using GWT's RPC to communicate with the server and the method that may throw an Exception declares it (void method() throws ...Exception) in the Service interface (the one that extends GWT's RemoteService), then you can catch the Exception in the onFailure(Throwable caught) method of your RPC callback and from there, take the appropriate action... if you want to redirect the user to another page, you could do:
Window.Location.assign(GWT.getHostPageBaseURL() + ERROR_PAGE);