Saturday, August 3, 2013

Rest Spring 3.1: Using RestTemplate For Get/Add/Update/Delete

Hi All,

I posted Sample with using RestTemplate, it is quite simple Example.
I have just implemented for Get, but Add,Update, Delete not yet.
Dowload Source code

-------------------------------------------------

package com.fpt.family.controller;

import org.springframework.stereotype.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.client.RestTemplate;

import com.fpt.family.dto.Father;
import com.jaxb.family.Family;

@Controller
public class FamilyController {

    private static RestTemplate restTemplate = new RestTemplate();

    private static final String serviceURL1 = "http://localhost:8080/springrestfuljaxb/ws/fpt/family/get";
    private static final String serviceURL2 = "http://localhost:8080/springrestfuljaxb/ws/fpt/family/get/";

    /**
     * Get All Family. You can implement for Mother, Children
     * 
     * @return
     */


    // http://localhost:8080/springrestful-client/getall
    @RequestMapping(value = "/getall", method = RequestMethod.GET)
    public @ResponseBody
    com.fpt.family.dto.Family getAll() {

    Family result = null;
    result = restTemplate.getForObject(serviceURL1, Family.class);

    Father father = new Father();
    father.setFatherName(result.getFather().getFatherName());
    father.setCompany(result.getFather().getCompany());

    com.fpt.family.dto.Family familyDto = new com.fpt.family.dto.Family();
    familyDto.setFather(father);

    return familyDto;
    }

    /**
     * 
     * Get family with flag.
     * 
     * @param flag
     * @return
     */

    // http://localhost:8080/springrestful-client/get/false
    // http://localhost:8080/springrestful-client/get/true
    @RequestMapping(value = "/get/{flag}", method = RequestMethod.GET)
    public @ResponseBody
    com.fpt.family.dto.Family getFamily(@PathVariable("flag") Boolean flag) {

    Family result = null;
    result = restTemplate.getForObject(serviceURL2 + flag, Family.class);
    if (flag) {
        Father father = new Father();
        father.setFatherName(result.getFather().getFatherName());
        father.setCompany(result.getFather().getCompany());

        com.fpt.family.dto.Family familyDto = new com.fpt.family.dto.Family();
        familyDto.setFather(father);
        return familyDto;
    } else {
        // Implelement
    }

    return null;
    }

}
Source Code