我正在开发一个生成报告供下载的GWT应用程序.当我在Eclipse中启动时,它有一个这样的URL:
http://127.0.0.1:8888/MyApp.html
但是当我打包我的应用程序以在Web服务器(即Tomcat)中部署时,我的URL是这样的:
HTTP://本地主机:8080/MyApp的/ MyApp.html
有没有办法获得应用程序的基本URL?像http:// localhost:8080/MyApp /在第二种情况下?
Str*_*lok 18
客户端:
GWT.getHostPageBaseURL();
Run Code Online (Sandbox Code Playgroud)
要么
GWT.getModuleBaseURL();
Run Code Online (Sandbox Code Playgroud)
在服务器端,您可以HttpServletRequest使用以下简单方法从中获取任何servlet的URL :
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();
}
}
Run Code Online (Sandbox Code Playgroud)
对于客户端,您可以使用Window.Location
例如:
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();
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用GWT Dictonary.在这里,您可以在主机HTML页面中包含一小段JavaScript来设置值:
<script type="text/javascript" language="javascript">
var location = { baseUrl: "http://localhost:8080/myapp" };
</script>
Run Code Online (Sandbox Code Playgroud)
然后使用GWT Dictionary将值加载到客户端:
Dictionary theme = Dictionary.getDictionary("location");
String baseUrl = theme.get("baseUrl");
Run Code Online (Sandbox Code Playgroud)
要使用它,您必须更改本地和生产实例的HTML主页.
doPoston的方法是RemoteServiceServlet通过HttpServletRequest客户端发送的。HttpServletRequest有许多可用的方法可以构造客户端请求的基本 URL。HttpServletRequest.getRequestURL() 从请求中检索整个 URL。如果您只需要基本 URL,而不需要页面名称,则可以使用getRemoteHost、getRemotePort和getServletPath的组合。
例子:
doPost(request, response){
String baseURL = new StringBuilder();
baseURL.append(request.getRemoteHost());
baseURL.append(":");
baseURL.append(request.getRemotePort());
baseURL.append(request.getServletPath());
}
Run Code Online (Sandbox Code Playgroud)