了解REST API-什么是上下文和@Context? [英] Understanding REST APIs - What are Context and @Context?

查看:304
本文介绍了了解REST API-什么是上下文和@Context?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近浏览了宁静的Web服务教程,但不了解上下文是什么.有人可以解释它的含义以及 @Contex t的含义吗?

I recently went through restful web services tutorial, but couldn't understand what a context is. Can someone explain what it it and also what @Context does?

推荐答案

JAX-RS提供@Context批注以注入与HTTP请求的上下文相关的12个对象实例,它们是:

JAX-RS provides the @Context annotation to inject 12 object instances related to the context of the HTTP request and they are:

  • SecurityContext -当前HTTP请求的安全上下文实例
  • 请求-用于设置前提条件请求处理
  • 应用程序配置提供程序->提供对JAX-RS应用程序,配置和提供程序实例的访问权限
  • ResourceContext -资源连接类实例
  • ServletConfig -ServletConfig实例实例
  • ServletContext -ServletContext实例
  • HttpServletRequest -当前请求的HttpServletRequest实例
  • HttpServletResponse -当前请求的HttpServletResponse实例
  • HttpHeaders -维护HTTP标头键和值
  • UriInfo -从称为URI的URI中查询参数和路径变量
  • SecurityContext - Security context instance for the current HTTP request
  • Request - Used for setting precondition request processing
  • Application, Configuration, and Providers -> Provide access to the JAX-RS application, configuration, and providers instances
  • ResourceContext - Resource contect aclass instances
  • ServletConfig - The ServletConfig instance instance
  • ServletContext - The ServletContext instance
  • HttpServletRequest - The HttpServletRequest instance for the current request
  • HttpServletResponse - The HttpServletResponse instance for the current request
  • HttpHeaders - Maintains the HTTP header keys and values
  • UriInfo - Query parameters and path variables from the URI called

同时具有@Inject(在Spring中为@Autowired)和@Context来完成相同的工作有点令人困惑,但是希望在下一版中为Java EE带来更多的统一性.同时,您将必须做.

It is a little confusing to have both an @Inject (or @Autowired in Spring) and @Context that does the same job, but it is hoped to bring more alignment to Java EE in the next edition. In the meantime, you will have to make do.

一个有趣的功能是,所有这些实例都可以作为字段值或直接注入到资源方法中.

An interesting feature is that all of these instances can be injected as a field value or directly into the resource method.

注入资源方法参数列表的示例:

An example of injection into the resource method parameter list:

@Path("/")
public class EndpointResource {

  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public Response getAllHttpHeaders(final @Context HttpHeaders httpHeaders){
      // Code here that uses httpHeaders
  }
}

向字段中注入的示例:

@Path("/")
public class EndpointResource {

  private final @Context HttpHeaders httpHeaders;

  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public Response getAllHttpHeaders(){
      // Code here that uses httpHeaders
  }
}

如果您想了解更多信息,请查看回答该问题的系列文章

If you want to know more, take a look at this series of articles answering the question What is @Conext in JAX-RS used for?

这篇关于了解REST API-什么是上下文和@Context?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆