Java 来自 REST 的访问请求对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1043346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:37:51  来源:igfitidea点击:

Access Request object from REST

javaweb-services

提问by qnoid

Is it possible to access the Request object in a REST method under JAX-RS?

是否可以在 JAX-RS 下以 REST 方法访问请求对象?

I just found out

我刚刚发现

@Context Request request;

采纳答案by dfa

On JAX-RS you must annotate a Requestparameter with @Context:

在 JAX-RS 上,您必须使用@Context注释请求参数:

 @GET  
 public Response foo(@Context Request request) {

 }

Optionally you can also inject:

(可选)您还可以注入:

回答by th3morg

To elaborate on @dfa's answer for alternatives, I find this to be simpler than specifying the variable on each resource method signature:

为了详细说明@dfa 对替代方案的回答,我发现这比在每个资源方法签名上指定变量更简单:

public class MyResource {

  @Context
  private HttpServletRequest httpRequest;

  @GET  
  public Response foo() {  
    httpRequest.getContentType(); //or whatever else you want to do with it
  }
}