Wednesday, 10 May 2017

Spring REST Web Service and Content Negotiation

com.spring.restful.controller.WebConfig.java
This customized class should be in the same package in which our controller exists because we are using <context:component-scan base-package="com.spring.restful" /> to scan the controller package.

We need to override the configureContentNegotiation method of the WebMvcConfigurerAdapter for content negotiations.
package com.spring.restful.controller;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
      /** Total customization. */
      @Override
      public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
            configurer.favorPathExtension(false).
            favorParameter(true).
            parameterName("mediaType").
            ignoreAcceptHeader(true).
            useJaf(false).
            defaultContentType(MediaType.APPLICATION_JSON).
            mediaType("xml", MediaType.APPLICATION_XML).
            mediaType("json", MediaType.APPLICATION_JSON);

      }
}

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns="http://java.sun.com/xml/ns/javaee"
      xmlns:web="http://java.sun.com/xml/ns/javaee"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
      id="WebApp_ID" version="2.5">
      <display-name>SpringRestFulService</display-name>
      <welcome-file-list>
            <welcome-file>index.html</welcome-file>
            <welcome-file>index.htm</welcome-file>
            <welcome-file>index.jsp</welcome-file>
            <welcome-file>default.html</welcome-file>
            <welcome-file>default.htm</welcome-file>
            <welcome-file>default.jsp</welcome-file>
      </welcome-file-list>
      <servlet>
            <servlet-name>rest</servlet-name>
            <servlet-class>
                  org.springframework.web.servlet.DispatcherServlet
            </servlet-class>
            <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
            <servlet-name>rest</servlet-name>
            <url-pattern>/*</url-pattern>
      </servlet-mapping>
</web-app>

rest-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:beans="http://www.springframework.org/schema/beans"
      xmlns:mvc="http://www.springframework.org/schema/mvc"
      xmlns:context="http://www.springframework.org/schema/context"
      xsi:schemaLocation="http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

      <!-- Enables the Spring MVC @Controller programming model -->
      <annotation-driven />

      <!-- for processing requests with annotated controller methods and set Message Convertors from the list of convertors -->
      <beans:bean
      class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
            <beans:property name="messageConverters">
                  <beans:list>
                        <beans:ref bean="jsonMessageConverter" />
                  </beans:list>
            </beans:property>
      </beans:bean>

      <!-- To convert JSON to Object and vice versa -->
      <beans:bean id="jsonMessageConverter"
      class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
      </beans:bean>
      <context:component-scan base-package="com.spring.restful" />

</beans:beans>

com.spring.restful.controller.UserDetailsService.java
package com.spring.restful.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.spring.restful.dao.UserDAO1;
import com.spring.restful.model.UsersDTO;

@RestController
public class UserDetailsService {

      @RequestMapping(value="/user/{msisdn}",
                  method = RequestMethod.GET,
                  produces={"application/xml", "application/json"})
      public @ResponseBody UsersDTO
                  getUserInformation( @PathVariable(value="msisdn")  String msisdn) {
           
            UsersDTO dto = UserDAO1.getUserDetail(msisdn);

            return dto;
      }

}

com.spring.restful.dao.UserDAO1.java
package com.spring.restful.dao;
import java.util.Date;
import com.spring.restful.model.UsersDTO;
public class UserDAO1 {
      public static UsersDTO getUserDetail(String msisdn) {
            /* we can fetch the user information from DB. */
            UsersDTO users = new UsersDTO();
            users.setUserId("123");
            users.setUserName("Rajesh");
            users.setDob(new Date());
            users.setMsisdn(msisdn);
            return users;
      }
}

com.spring.restful.dao.UsersDTO.java
package com.spring.restful.model;
import java.util.*;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class UsersDTO {

      private String userId;
      private String userName;
      private Date dob;
      private String msisdn;
     
      @XmlElement
      public String getUserId() {
            return userId;
      }
      public void setUserId(String userId) {
            this.userId = userId;
      }
     
      @XmlElement
      public String getUserName() {
            return userName;
      }
      public void setUserName(String userName) {
            this.userName = userName;
      }
     
      @XmlElement
      public String getMsisdn() {
            return msisdn;
      }
      public void setMsisdn(String msisdn) {
            this.msisdn = msisdn;
      }
     
      @XmlElement
      public Date getDob() {
            return dob;
      }
      public void setDob(Date dob) {
            this.dob = dob;
      }
}

Note:
For XML binding, we need to put annotation on the DTO class fields.
For json response, we need to put the jackson-mapper  jars in class path only.


Sample Request to fetch the data:

Jar needed:
Spring core jar
Spring web jar
commons-logging-1.1.1.jar
jackson-annotations-2.5.4.jar
jackson-core-2.2.0.jar
jackson-databind-2.1.4.jar
jaxb-api-2.2.jar for XML binding
jstl-1.2.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...