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.
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.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