What is context variable in java

Digital Transformation and Java Video Training

Java | Integration | MuleSoft | Digital Transformation | API-led connectivity | RESTful API

JAX-RS: What is @Context?

Posted on August 22, 2017 by Alex in Java EE, JAX-RS // 0 Comments

Inject Twelve Context Object

The JAX-RS API from the Java EE ecosystem of technologies provides the annotation @Context, to inject 12 object instances related to the context of the HTTP request. It behaves just like to @Inject and the @Autowired annotations in Java EE and Spring respectively.

The object instances that it can inject are the following:

  • 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 context class 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

It is a little confusing to have both an @Inject and @Context when both do the same job of injecting objects, but it is envisioned that future version of Java EE will bring more alignment of annotation use.

Читайте также:  Media queries css шпаргалка

Where is @Context Used?

It can be used to inject any of the about mentioned instances into an instance field or directly into the resource method as a parameter.

Below is an example of the injecting into a method’s resource method parameter list:

@Path("/") public class EndpointResource < @GET @Produces(MediaType.APPLICATION_JSON) public Response getHeaders(final @Context HttpHeaders httpHeaders)< // Code here that uses httpHeaders >>

And here’s an example of injection into an instances field:

@Path("/") public class EndpointResource < private final @Context HttpHeaders httpHeaders; @GET @Produces(MediaType.APPLICATION_JSON) public Response getHeaders()< // 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?

Code Repository

The source code for this article is in my GitHub repository. Code for all my articles is in the ReadLearnCode Articles repository.

Further Reading

I often publish articles about Java EE on readlearncode.com and have posted an interesting series of blog articles looking at the JAX-RS API in more detail. These articles discuss handling bean validation failure, working with @Consumes and @Produces annotations, and JAX-RS Resource Entities, and take you deeper into this core Java API.

Learn More

Have you considered online video training from Lynda.com? The site offers an extensive range of Java EE technologies course for beginners to experts. So, if you are just taking your first steps into the exciting world of enterprise Java then you will love my course Learning Java Enterprise Edition. It is a packed full two-hour course spanning the essential APIs in the Java EE platform.

Your learning does not end with this course. Once completed, you can expand your knowledge by learning how to build an online bookshop using RESTful APIs, build your own chat application with the WebSocket API and become a JSON master with the JSON-Processing course. There are many more courses on the roadmap, so pop over to Lynda.com and get ready to give your Java EE career a boost.

Источник

Almighty Java

If you have a doubt, means you are learning something 🙂

Almighty Java

What is a context in Java ?

  • A context can be said as the running environment that is provided to the current unit of work. It may be the environment variables, instance variables, state of the classes, and so on.
  • Like ServletContext represents the servlet’s environment within its container, Similar to ApplicationContext, which represents the Spring application’s core environment within the Spring container.
  • There are Servlet’s ServletContext, JSF’s FacesContext, Spring’s ApplicationContext, JNDI’s InitialContext, and all these contexts follow the Facade Pattern to Abstract the environment specific details to the end user, providing the interface methods to Interact with.

Spring Context Configuration

In Spring web applications, there are two contexts that get initialized at server startup, each of which is configured and initialized differently.

1.Application Context

2.Web Application Context

What is Application Context?

  • ApplicationContext defines the beans that are shared among all the servlets.
  • In ApplicationContext, Spring loads applicationContext.xml file and creates the context for the whole application using ContextLoaderListener that we define in our application’s web.xml.
  • applicationContext.xml is the root context configuration for every web application There will be only one application context per web application.
  • If you are not explicitly declaring the context configuration file name in web.xml using the contextConfigLocation param, Spring will search for the applicationContext.xml under WEB-INF folder and throw FileNotFoundException, if it could not find this file.
  • Beans that defines your business logic, database interaction and other stuff that has to be shared across servlets should reside in applicationContext.xml.

This is the part of web.xml file

 org.springframework.web.context.ContextLoaderListener  contextConfigLocation /WEB-INF/root-context.xml 

In the above configuration, we are asking Spring to load root-context.xml and create an Application Context from it.

If contextConfigLocation is not mentioned as in the above snippet, It will by default look for

At server startup, ContextLoaderListener instantiates all bean defined in applicationcontext.xml assuming you have defined the following in context XML file :

The beans are instantiated from all four configuration files test1.xml, test2.xml, test3.xml, test4.xml

What is WebApplicationContext?

  • There can be multiple WebApplicationContext in a single web application.
  • It is another servlet specific context that is loaded based on the dispatcher servlets configured in the application’s web.xml file.
  • Each dispatcher servlet has its own servlet-context initialized from -servlet.xml file.
  • This allows us to categorize the incoming requests based on the servlet’s URL-pattern and handle them accordingly, such that one of the dispatcher servlets could help serving the web pages via Controller, while another one could be used to implement a stateless REST web service.
  • We understand that a single web application can have multiple dispatcher-servlet configurations.
  • dispatcher-servlet.xml defines the beans that are related only to that servlet. Beans that deals with servlet requests/web requests like controllers, message converters, interceptors should reside in dispatcher-servlet XML.

If we want to change the name of the dispatcher-servlet file name or change its location, we can add init-param with contextConfigLocation as param-name, as can be seen below

 spring org.springframework.web.servlet.DispatcherServlet contextConfigLocation /WEB-INF/spring-servlet.xml  1  spring / 

So with spring-servlet init-param specified as in the above web.xml code snippet, Spring no more finds the dispatcher-servlet context file with the name spring-servlet.xml, but instead looks for the one specified as the init-param value for contextConfigLocation, i.e. spring-servlet.xml.

Object creations workflow

  • When tomcat starts, beans defined in dispatcher-servlet.xml are instantiated.
  • DispatcherServlet extends FrameworkServlet. In FrameworkServlet bean instantiation takes place for the dispatcher. In our case dispatcher is FrameworkServlet.
  • The beans are all instantiated from all four test1.xml, test2.xml, test3.xml, test4.xml. After the completion of bean instantiation defined in applicationcontext.xml then beans defined in dispatcher-servlet.xml are instantiated.
  • Instantiation order is root is application context, then FrameworkServlet.

Difference between the two contexts

  • ApplicationContext is the root-context that has bean configurations we might want to use (and re-use) across the entire application as singletons.
  • There can be multiple WebApplicationContexts for each of the dispatcher servlets we specify in our application’s web.xml.
  • WebApplicationContext internally extends ApplicationContext, and as a child inherits all the beans from its parent. So we can also override the parent bean within our WebApplicationContext.
  • It’s always better to keep a clear separation between middle-tier services such as business logic components and data access classes (which we prefer defining in the ApplicationContext XML), and web-related components such as controllers and view-resolvers (which we prefer defining in the respective dispatcher-servlet‘s WebApplicationContext).
  • Configuring contextLoaderListener is completely optional. We can boot up a Spring application with just the dispatcher-servlet, without even configuring contextLoaderListener (that loads up the root-context).

For more detail, Please watch below video –

Please Subscribe our you tube channel Almighty Java

Источник

Оцените статью