How to Extract Ip Address in Spring MVC Controller Get Call

How can I get the client IP address of requests in Spring Boot?

I've used a different way to get the addresses of my client requests.

I've created a class called WebConfig that implements WebMvcConfigurer. This class configures some usages in spring. and here's the code for this class:

@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoggerInterceptor());
}
}

This method is registering an interceptor, this interceptor will intercept the requests and using methods you will create it will execute when some request is send. For exemple my code:

public class LoggerInterceptor extends HandlerInterceptorAdapter {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) {

System.out.println(request.getRemoteAddr());
return true;
}
}

In my case I've used "preHandle" method to get the Ip of my client request, this method is called every time someone calls my application via request and before spring handles the request my method is called, it can be used as a security configuration as well, because you can return false, in that case the request won't execute. But for that usage there's others ways with spring boot.

If I'm doing something wrong please correct me.

Spring MVC controller method called for GET but not for POST

newer spring security versions enable csrf by default which leads to strange errors sometimes. Try disabling by .csrf().disable() in your security config or look here: https://www.baeldung.com/spring-security-csrf

Get the request sending URL in spring

X-Forwarded-For value gives you the IP address of client. You can get the IP like below in spring.

String remoteAddress = request.getHeader("X-Forwarded-For");//request--HTTPServletRequest Object
if (remoteAddress == null) {
remoteAddress = request.getRemoteAddr();
}

spring security: NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.config.annotation.ObjectPostProcessor] found

The problem is that you do not have @EnableWebSecurity annotation on your SecurityConfiguration class.

This would have been added by Spring-boot automatically, however since you opted for not using Spring-boot this needs to be taken care of manually.



Related Topics



Leave a reply



Submit