I'm developing a GWT App which generates reports for download. When I launch in Eclipse it has an URL like this:
http://127.0.0.1:8888/MyApp.html
But when I package my app for deployment in a web server (i.e. Tomcat) my URL is like this:
http://localhost:8080/MyApp/MyApp.html
Is there any way to get the app's base URL? Like http://localhost:8080/MyApp/ in the second case?
Client side:
GWT.getHostPageBaseURL();
or
GWT.getModuleBaseURL();
Server side you can get the URL of any servlet from the HttpServletRequest
by using this simple method:
public static String getBaseUrl( HttpServletRequest request ) {
if ( ( request.getServerPort() == 80 ) ||
( request.getServerPort() == 443 ) ) {
return request.getScheme() + "://" +
request.getServerName() +
request.getContextPath();
} else {
return request.getScheme() + "://" +
request.getServerName() + ":" + request.getServerPort() +
request.getContextPath();
}
}
For client side you can use Window.Location
For example:
public static String getUrlString(String path) {
UrlBuilder urlBuilder = new UrlBuilder();
urlBuilder.setHost(Window.Location.getHost());
urlBuilder.setPath(path);
String port = Window.Location.getPort();
if (!port.isEmpty())
urlBuilder.setPort(Integer.parseInt(port));
return urlBuilder.buildString();
}
Another approach is to use GWT Dictonary. Here you include a snippet of JavaScript in your host HTML page to set the value:
<script type="text/javascript" language="javascript">
var location = { baseUrl: "http://localhost:8080/myapp" };
</script>
Then load the value into the client side with GWT Dictionary:
Dictionary theme = Dictionary.getDictionary("location");
String baseUrl = theme.get("baseUrl");
To use this you would have to change the HTML host page for your local and production instances.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With