Develop MEAN Stack Application

I have recently written a guest blog about developing a MEAN stack application at http://javabeginnerstutorial.com.

Refer the link MEAN Comments Application to read that post.

Refer the link meanstack-comments-application for the code base.

Advertisements

How to get Application HostName and client ip address in Java

Consider the below example,

We have an AngularJs web application and the backend is Java RESTful API.

So the application flow will be like this,
Client ==> AngularJs==> RESTful API

Assume that we have two RESTful services. They are /api/document to retrieve the document details and /api/download to download the document content in a PDF. Assume that we want to generate the download service link in the /api/document service response something like below,

/api/document?docId=1
{
	"docId": "1",
        "data":"",
	"downloadLink": "https://app-dev.com/api/download?type=pdf&docId=1"
}

Here the app-dev.com represents the host name of the application.

So to get the host name, we have to retrieve the ‘x-forward-host’  HTTP header as we can’t depend on the host header as it may be modified by the intermediate proxy server. Refer below the code to retrieve the hostname.


     public String getHost(HttpServletRequest servletRequest) {
          return servletRequest.getHeader("x-forwarded-host");
    }

To get the client IP address, we have to retrieve the ‘x-forwarded-for’ header. The general format of this field is X-Forwarded-For: client, proxy1, proxy2. So if there are any proxy servers in between the client and application, then those proxies IP address are appended to this header. So always use the first IP address available in this header to know the actual client IP address.


     public String getClientIpAddress(HttpServletRequest servletRequest) {
          return servletRequest.getHeader("X-Forwarded-For").split(",")[0];
    }