Content negotiation example using Spring Boot

In this article, we will see Content negotiation example using Spring Boot. First, we will see what is content negotiation, how to configure the content negotiation mechanism in real time development using spring boot. Let’s see what is content negotiation and how to configure it.

Content negotiation example using Spring Boot

  • Content negotiation means what type of data you want to produce or consume. It may be JSON or XML.
  • For configuring content negotiation, we need to add a dependency in pom.xml.

  • We need to add produces = {“application/xml”} in @RequestMapping annotation.

  •  Or we can configure content negotiation globally using WebMvcConfigurerAdapter(A predefined class available in org.springframework.web.servlet.config.annotation package) as below.

We will have

Let’s see an example where we are going to produce XML data as a response.

Step 1 – open eclipse and create maven project, Don’t forget to check ‘Create a simple project (skip)click on next.

Step 2 –  Fill all details as below and click on finish.

 

Step 3 – Create the below directory structure, open pom.xml and add the required dependency.

Content negotiation example using Spring Boot

 

 

Modify pom.xml.

 

Step 3 – Define classes.

Book.java

 

BookController.java

 

SpringMain.java

 

Configure WebMvcConfigurerAdapter class and override configureContentNegotiation method.

WebConfigAdapter.java

 

Define the port in application.properties.

server.port = 9091

 

Step 4 – Run the SpringMain.java and deploy our application.

Content negotiation example using Spring Boot

 

Step 5 – Test the rest URI.

 

We have the response as XML. Did you notice in the above example we have written  produces = {“application/xml”} in BookController.java and commented the code inside WebConfigureAdapter class.

In this approach, we need to define  produces = {“application/xml”} with each request URI. Suppose we know our application only can produce XML data as the response. We no need to define produces = {“application/xml”} with each resource. We can configure globally what kind of data we want to produce. Let’s do some small modification in BookController.java and WebConfigAdapter.java.

  • Remove produces = {“application/xml”} from request URI.
  • Override configureContentNegotiation() method in WebConfigAdapter.java class.
  • Run the SpringMain.java and deploy the application. We will have the same output i.e xml data we will have as response.

 

That’s all we have about Content negotiation example using Spring Boot.

you may like –

 

 

 

Top