Accessing HttpServletRequest in normal Java class


Accessing HttpServletRequest in normal Java class 


Hi, I am Malathi Boggavarapu working at Volvo Group and i live in Gothenburg, Sweden. I have been working on Java since several years and had vast experience and knowledge across various technologies.

Recently i came across the situation at work where i need to access HttpServletRequest in a normal Java class inorder to get Ip Address from the request. In my normal Java class i do not have direct access to the request and hence i used the below code to do that. But the normal Java class should be the part of HttpServlet request thread. It means that the normal Java class is being called from a HttpServlet request thread.

ServletRequest servletRequest = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
if(servletRequest instanceOf HttpServletRequest) {
   ipAddress =  ((HttpServletRequest)request).getHeader("X-Forwarded-For");
}
if(ipAddress == null) {
    ipAddress = request.getRemoteAddr();
}

Hope it is helpful. Please post your comments for any questions.

Comments

Popular posts from this blog

Bash - Execute Pl/Sql script from Shell script

Gradle Fundamentals

Load Balancing using Spring Cloud Netflix Ribbon