Posts

Showing posts with the label RequestContextHolder

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)