google Analytics

Wednesday, September 22, 2010

RESTEasy and Spring MVC

JBoss RESTEasy and Spring MVC
REST with Spring



example
=============================================================
 

package com.test;
import java.net.URI;
import java.net.URISyntaxException;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;

import org.jboss.resteasy.annotations.Form;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
/**
 *
 * @author NathA1
Spring will use any class annotated with the @Controller annotation as
a Controller in Spring MVC support
The @Produces is used to map a client request and match it up to the client's Accept header.
The Accept HTTP header is sent by the client and defines the media types the client prefers to
receive from the server
 */
@Controller
@Path(ProductsResource.CONTACTS_URL)
public class ProductsResource
{
   public static final String CONTACTS_URL = "/products";
   @Autowired
   ProductService service;

   @GET
   @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
   @Path("data")
   public Products getAll()
   {
      return service.getAll();
   }

   @PUT
   @POST
   @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
   @Path("data")
   public Response saveProduct(@Context UriInfo uri, Product product)
         throws URISyntaxException
   {
       System.out.println("Inside -->> saveProduct");
      service.save(product);
      URI newURI = UriBuilder.fromUri(uri.getPath()).path(product.getLongName()).build();
      return Response.created(newURI).build();
   }

   @GET
   @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
   @Path("data/{shortName}")
   public Product get(@PathParam("shortName") String shortName)
   {
      return service.getProduct(shortName);
   }

   @POST
   @PUT
   @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
   @Produces(MediaType.TEXT_HTML)
   public ModelAndView saveContactForm(@Form Product product)
         throws URISyntaxException
   {
       System.out.println("Inside -->> saveContactForm");
      service.save(product);
      return viewAll();
   }
  

   @GET
   @Produces(MediaType.TEXT_HTML)
   public ModelAndView viewAll()
   {
      // forward to the "contacts" view, with a request attribute named
      // "contacts" that has all of the existing contacts
      return new ModelAndView("products", "products", service.getAll());
   }
}
/**
 * END OF PROGRAM
 * =======================================================================
package com.test;
import java.util.ArrayList;
import java.util.Collection;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
When a class is annotated with a @XmlRootElement annotation, RESTEasy
will select the JAXBXmlRootElementProvider. This provider handles basic marhaling and and
unmarshalling of custom JAXB entities
@author Anish Nath
 *
 */

@XmlRootElement
public class Products
{
   private Collection<Product> products;
   public Products()
   {
      this.products = new ArrayList<Product>();
   }
   public Products(Collection<Product> products)
   {
      this.products = products;
   }
   /**
    *  @XmlElement annotation to embed other JAXB-annotated classes.
    * @return
    */
   @XmlElement(name="product")
   public Collection<Product> getProducts()
   {
      return products;
   }
   public void setProducts(Collection<Product> product)
   {
      
      this.products = product;
   }
}

/**
 * END OF PROGRAM
 * =======================================================================
 */
package com.test;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.stereotype.Service;
/**
 *
 * Anish Nath
The @Service annotation marks classes that implement a part of the business
logic of the application
 *
 */
@Service
public class ProductService
{
   private Map<String, Product> productMap = new ConcurrentHashMap<String, Product>();
   public void save(Product product)
   {
       productMap.put(product.getShortName(), product);
   }
   public Product getProduct(String shortName)
   {
      return productMap.get(shortName);
   }
   public Products getAll()
   {
      return new Products(productMap.values());
   }
}

/**
 * END OF PROGRAM
 * =======================================================================
 */
 Web.xml
<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

    <servlet>

        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/products/*</url-pattern>
    </servlet-mapping>

</web-app>

==========================================================================
springmvc-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    ">
    <context:component-scan base-package="com.test" />
    <context:annotation-config />
    <import resource="classpath:springmvc-resteasy.xml" />
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

===========================================================================================
spring rest services
spring rest example

RESTfull web service Example
restlet spring security
ANish

2 comments:

  1. can we download the programme as zip file

    ReplyDelete
  2. This article has been stolen from some one else's post.

    ReplyDelete