Reputation: 3709
In my Spring boot project, I have made some some RESTful APIs. Now, for each request in my APIs, I want to set a specific header like below below-
If the Http request is called with that specific header name and header value, only then it will show response code ok(200) otherwise it will show some other response code.
I need one single configuration to fix that specific header for each request in my project. So, I need some suggestion about the procedure to follow to solve this issue.
Upvotes: 0
Views: 791
Reputation: 1467
I think in these kind of scenarios if you want to handle them in single point filters are good choices
I hope below code can give you the idea how to use filter to solve your problem:
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class HeaderCheckerFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String header = request.getHeader("MyHeader");
if (header != null && header.equals("HeaderValue")) {
filterChain.doFilter(request, response);
} else {
response.getWriter().println("invalid request");
}
}
}
Upvotes: 2