Search code examples
gwtcdnsame-origin-policy

How to serve GWT static files from a CDN


I am trying to figure out how to serve my GWT files from a CDN instead of from a tomcat server.

I started with this code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="robots" content="no-index, no-follow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My Site</title>
<script type="text/javascript" src="/bcmjs/bcmjs.nocache.js"></script>
</head>

<body>
<div id="gwt_div">
</div>
</body>
</html>

And modified the javascript import to use the CDN url, from this:

<script type="text/javascript" src="/bcmjs/bcmjs.nocache.js"></script>

To this:

<script type="text/javascript" src="https://uoo9w.cloudfront.net/bcmjs/bcmjs.nocache.js"></script>

Hoorah! The js downloads, UIBinder widgets are visible, but RPC fails.

The problem seems to be that GWT.getModuleBase returns the URL of the Javascript (uoo9w.cloudfront.net) instead of the host page (mysite.example.com), which breaks things like the URL used for RPC requests.

GWT.getModuleBaseForStaticFiles seems to be a method built allow CDN use, but I can't find documentation about it. (See comments)

Does anyone know of the correct way to set up GWT to serve from a CDN and send RPC request to the host page's domain?

Side Note:

Since the CDN has a different domain name and path, I was worried there were going to be problems involving the Same Origin Policy, but since the GWT host page is served on the same domain as all the RPC requests, this is not a problem. (ie. Window.Location is the same domain as the RPC)


Solution

  • GWT sets the url of RPCs pointing to the src attribute of the modulename.nocache.js script-tag instead of the location of your document.

    The normal way to fix it is that you change the base url of your rpc service to point to the location of your html file

    GreetingServiceAsync greetingService = GWT.create(GreetingService.class);
    ((ServiceDefTarget)greetingService)
       .setServiceEntryPoint("http://hostname_of_your_document/modulename/greet");
    

    NOTE: in this case you are not doing crossdomain since your .html and your services are in the same host.

    OPTIONALLY, if the services weren't in the same host than the .html file, you were doing crossdomain, so you might configure your servlet to support CORS. The best way is to configure a filter in your web.xml

    <filter>
      <filter-name>corsFilter</filter-name>
      <filter-class>com.example.server.CORSFilter</filter-class>
    </filter>
    <filter-mapping>
      <filter-name>corsFilter</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>
    

    For the filter class you can take the example I did for the gwtquery Ajax documentation