How to get access to HTTP header information in Spring MVC REST controller?

Horse Voice picture Horse Voice · Oct 24, 2013 · Viewed 186.4k times · Source

I am new to web programming in general, especially in Java, so I just learned what a header and body is.

I'm writing RESTful services using Spring MVC. I am able to create simple services with the @RequestMapping in my controllers. I need help understanding how to get HTTP header information from a request that comes to my method in my REST service controller. I would like to parse out the header and get some attributes from it.

Could you explain how I go about getting that information?

Answer

Vidya picture Vidya · Oct 24, 2013

When you annotate a parameter with @RequestHeader, the parameter retrieves the header information. So you can just do something like this:

@RequestHeader("Accept")

to get the Accept header.

So from the documentation:

@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
                              @RequestHeader("Keep-Alive") long keepAlive)  {

}

The Accept-Encoding and Keep-Alive header values are provided in the encoding and keepAlive parameters respectively.

And no worries. We are all noobs with something.