Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Spring 4 Restful Web Services

Tags: import

Spring 4 introduces @RestController which is combination of @Controller and @ResponseBody annotations.

Quick Introduction to Rest

REST stands for Representational State Transfer which is common way of sharing information between two applications build on any programming languages,any platform etc.

Example of Rest Application

In this turorial, we get to know how to create simple rest application in Spring 4.  Here we’re dealing to create json and XML responses.

Required Jars

  1. Spring 4.2.0.RELEASE
  2. jackson-annotations-2.6.3.jar
  3. jackson-core-2.6.3.jar
  4. jackson-databind-2.6.3.jar

Like our Spring MVC 4 Example  post we are doing  java file configuration using annotation rather than XML configuration.

Spring MVC 4 Configuration

Spring MVC 4 has replaced XML configuration with Java file configuration. You can use either one of them to build web application.

Here we’re defining contentNegotiatingViewResolver bean to defines various types viewresolvers to generates different views JSP,XML or json.

ContentNegotiatingViewResolver, is view resolver that provides way to generate different views JSP,XML,JSON,XLS,PDF etc as per requested content. It first check through requested file extension, then checks for accepted media types.

AppConfig.java

package com.expertwebindia.services;
import java.util.ArrayList;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

import com.expertwebindia.controllers.Test;

@Configuration 
@ComponentScan(basePackages = {"com.expertwebindia.controllers","com.expertwebindia.services"}) 
@EnableWebMvc   
public class AppConfig {  
    @Bean  
    public ViewResolver contentNegotiatingViewResolver(  
                    ContentNegotiationManager manager) {  
            List< ViewResolver > resolvers = new ArrayList< ViewResolver >();  
            
            //For JSP Views
            InternalResourceViewResolver r1 = new InternalResourceViewResolver();  
            r1.setPrefix("/WEB-INF/views/");  
            r1.setSuffix(".jsp");  
            r1.setViewClass(JstlView.class);  
            resolvers.add(r1);  
            
            //For JSON views 

            JsonViewResolver r2 = new JsonViewResolver();  
            resolvers.add(r2);  
            
            //For XML views 
            Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
            Jaxb2MarshallingXmlViewResolver jaxb2MarshallingXmlViewResolver =  new Jaxb2MarshallingXmlViewResolver(marshaller);
            resolvers.add(jaxb2MarshallingXmlViewResolver);
            
            ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();  
            resolver.setViewResolvers(resolvers);  
            resolver.setContentNegotiationManager(manager);  
            return resolver;  
    } 
} 

Defining ViewResolvers

We have two view resolvers here.

  1. For XML
  2. For JSON

Jaxb2MarshallingXmlViewResolver.java

package com.expertwebindia.services;
import java.util.Locale;
import org.springframework.oxm.Marshaller;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.xml.MarshallingView;

public class Jaxb2MarshallingXmlViewResolver implements ViewResolver {

private Marshaller marshaller;

public Jaxb2MarshallingXmlViewResolver(Marshaller marshaller) {
this.marshaller = marshaller;
}
public View resolveViewName(String viewName, Locale locale)
throws Exception {
MarshallingView view = new MarshallingView();
view.setMarshaller(marshaller);
return view;
}

}

JsonViewResolver.java

package com.expertwebindia.services;

import java.util.Locale;

import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

public class JsonViewResolver implements ViewResolver{

@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
MappingJackson2JsonView view = new MappingJackson2JsonView();
view.setPrettyPrint(true);
return view;
}

}

Configuring Dispatcher Servlet and Associating AppConfig

WebAppInitializer.java

package com.expertwebindia.services;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class WebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(AppConfig.class);
ctx.setServletContext(servletContext);
ctx.setConfigLocation("/WEB-INF/dispatcher-servlet.xml");
Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
dynamic.addMapping("/");
dynamic.setLoadOnStartup(1);
}
}

Defining POJO class

Product POJO class is annotated with JAXB annotations to facilitate XML response.

Product.java

package com.expertwebindia.beans;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="product")
public class Product {
private int id;
private double price;
private String name;
public Product() {
super();
}
public Product(int id, String name,double price) {
super();
this.id = id;
this.price = price;
this.name = name;
}
@XmlElement
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@XmlElement
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}

Defining Controller for Rest Services

ProductService.java

package com.expertwebindia.services;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.expertwebindia.beans.Product;
import com.expertwebindia.beans.Stock;
import com.expertwebindia.controllers.Test;
import com.expertwebindia.dao.ProductDao;
@RestController
@RequestMapping("/services/product/")
public class ProductService {
@RequestMapping(value = "/list", method = RequestMethod.GET)
public ResponseEntity<List<Product>> listAllProducts() {
List productsList = new ArrayList<Product>();
productsList.add(new Product(1,"A",100));
productsList.add(new Product(2,"B",200));
productsList.add(new Product(3,"C",300));
productsList.add(new Product(4,"C",400));
return new ResponseEntity<List<Product>>(productsList, HttpStatus.OK);
}
@RequestMapping(value = "/listXML", method = RequestMethod.GET,produces = "application/xml")
public ResponseEntity<Stock> listPiza() {
Stock stock = new Stock();
List productsList = new ArrayList<Product>();
productsList.add(new Product(1,"A",100));
productsList.add(new Product(2,"B",200));
productsList.add(new Product(3,"C",300));
productsList.add(new Product(4,"C",400));
stock.setProducts(productsList);
return new ResponseEntity<Stock>(stock, HttpStatus.OK);
}
}

Output JSON Response

We have to invoke the following URI to get the JSON response.

http://localhost:8080/Spring4WebService/services/product/list

Spring 4 restful web services

Output XML Response

We have to invoke the following URI to get the XML response.

http://localhost:8080/Spring4WebService/services/product/listXML

Spring 4 restful web services

 



This post first appeared on Expertwebindia|Online Web Solutions, please read the originial post: here

Share the post

Spring 4 Restful Web Services

×

Subscribe to Expertwebindia|online Web Solutions

Get updates delivered right to your inbox!

Thank you for your subscription

×