26 November, 2012

Java/JEE: How to get an asset on a web server behind the firewall?


Usage of  request.getLocalName() vs request.getServerName() to get an asset
Here the scenario is accessing the assets like images, templates etc used in a web application.
The "/asset" is a server side program which returns the asset file content by taking a asset file name as input. In this case the assets are kept on the same web server where the web application runs.
There are two methods available to get the name of the server.
1) The request.getServerName() method returns the name of the server that the HTTP request was sent to.
2) The request.getLocalName() method returns the name of the server that actually received the request.
The request.getServerName() which returns the name of the public server on the firewall, but not the web server. So we cannot access the asset.

The request.getLocalName() which returns the name of the web server that received the request, so we access the asset on the web server behind the firewall.

Code Snippet

public static String getAssetUrl(HttpServletRequest request, String fileName) {
    String scheme = request.getScheme();
    String localServerName = request.getLocalName();
    int localServerPort = request.getLocalPort();
    String contextPath = request.getContextPath();
    String pathInfo = request.getPathInfo();

    // Reconstruct original request URL
    String url = scheme + "://" + localServerName + ":" + localServerPort
        + contextPath + "/asset?fileName=/" + fileName;

    if (pathInfo != null) {
        url += pathInfo;
    return url;

No comments:

Post a Comment