简体   繁体   中英

How to handle HTTP headers in Spring MVC?

in this period I am studying the Spring MVC showcase example. Now I am studying how Spring MVC requires data.

I have some difficulties to understand how HTTP Request header are handled.

In pratcice I have the following link:

<a id="header" class="textLink" href="<c:url value="/data/header" />">Header</a>

This link generate an HTTP Request towards the URL: "/data/header"

This is the method of the RequestDataController class that handles this HTTP Request (the entire class is annoted by @RequestMapping("/data"): so this method handle /data/header URL)

@RequestMapping(value="header", method=RequestMethod.GET)
public @ResponseBody String withHeader(@RequestHeader String Accept) {
    return "Obtained 'Accept' header '" + Accept + "'";
}

So the withHeader method take a parameter that is annoted by @RequestHeader annotation that is an annotation which indicates that a method parameter should be bound to a web request header.

Ok, so my answer is: what exactly I have inside the Accept variable? The value of my HTTP Accetp Header? or what?

Fow what I know Accept request-header field can be used to specify certain media types which are acceptable for the response. Accept headers can be used to indicate that the request is specifically limited to a small set of desired types, as in the case of a request for an in-line image.

So my output (the returned value) is: Obtained 'Accept' header 'text/plain, / ; q=0.01'

mmm...what it exactly means this Accept headers field value?

Thank you

Andrea

Yes, when you annotate a parameter with @RequestHeader, the parameter name is used for retrieving the header information - in your case that will be the header name of 'Accept'- the parameter name could have been accept also, the header names are retrieved in a case insensitive manner.

You could have also explicitly specified the header name explicitly this way: @RequestHeader("Accept")

Accept header like you have indicated is a way for the client(browser) to say what it can accept as a media type of the response to be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM