如何访问 Spring MVC REST 控制器中的 HTTP 标头信息?

问题描述:

总的来说,我是网络编程的新手,尤其是 Java,所以我刚刚了解了标题和正文是什么.

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

我正在使用 Spring MVC 编写 RESTful 服务.我能够在我的控制器中使用 @RequestMapping 创建简单的服务.我需要帮助了解如何从我的 REST 服务控制器中的方法的请求中获取 HTTP 标头信息.我想解析标题并从中获取一些属性.

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?

当您使用 @RequestHeader 注释参数时,该参数会检索标头信息.所以你可以做这样的事情:

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

@RequestHeader("Accept")

获取Accept 标头.

因此来自 文档:

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

}

Accept-EncodingKeep-Alive 标头值分别在 encodingkeepAlive 参数中提供.

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.