본문 바로가기
개발

Spring Boot에서 응답 헤더 서버 이름 설정하는 방법

by 농담곰이 2023. 5. 5.
반응형

스프링 부트(Spring Boot)에서 응답 헤더(Response Header)의 서버 이름(Server Name)을 설정하려면 커스텀 `Filter`를 구현하고 이를 애플리케이션에 추가해야 합니다. 아래 예제에서는 응답 헤더의 "Server" 속성 값을 "My Custom Server"로 설정하는 방법을 보여줍니다.


1. CustomServerNameFilter 클래스 작성:

새로운 `CustomServerNameFilter` 클래스를 생성하고 `Filter` 인터페이스를 구현합니다.

```java
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CustomServerNameFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader("Server", "My Custom Server");

        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }
}
```

2. CustomServerNameFilter 빈 등록:

`CustomServerNameFilter`를 스프링 애플리케이션에 빈(Bean)으로 등록하려면 `@Bean` 어노테이션을 사용합니다. 애플리케이션의 메인 클래스 또는 구성 클래스에 아래 코드를 추가합니다.

```java
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean
    public FilterRegistrationBean<CustomServerNameFilter> customServerNameFilter() {
        FilterRegistrationBean<CustomServerNameFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new CustomServerNameFilter());
        registrationBean.addUrlPatterns("/*");

        return registrationBean;
    }
}
```

이제 스프링 부트 애플리케이션이 실행되면 모든 응답 헤더에 "Server" 속성이 "My Custom Server"로 설정되어 있습니다. 원하는 서버 이름으로 값을 변경할 수 있습니다.

반응형

댓글