본문 바로가기

spring

Spring을 이용한 RESTful 서비스 2


2012/07/11 - [spring] - Spring을 이용한 RESTful 서비스 1에서 서비스를 구현했으니 이 서비스를 Spring의 RestTemplate을 이용하여 클라이언트를 구현하는 방법입니다. 예전에 만든 RESTful 서비스는 아래와 같이 구성되어 있습니다. 목록, 입력, 삭제만 사용해보겠습니다. 

 Action

 Resource

 Method

 

 /memos

 GET

 보기

 /memos/{seq}

 GET

 입력

 /memos

 POST

 수정

 /memos/{seq}

 PUT

 삭제

 /memos/{seq}

 DELETE

서비스를 이용하기 위해서 Spring 설정파일에 RestTemplate을 정의합니다. 클래스에서 RestTemplate template = new RestTemplate(); 처럼 인스턴스 직접 생성하셔도 상관없습니다. 

messageConverter를 사용할것이기때문에 <mvc:annotation-driven/>도 정의해줍니다.

spring-servlet.xml

<mvc:annotation-driven/>

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate" />

jsp 파일을 아래와 같이 구성합니다.

list.jsp

<%@ page language="java" pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>

<%

/**

 * TEST

 * @author francis Lee

 * @since 2012. 07. 11.

 */

%>

<!DOCTYPE html>

<html lang="ko">

<head>

<meta charset="utf-8">

<title>TEST</title>

<style type="text/css">

body {

    font-family: "Malgun Gothic","돋움","Trebuchet MS","Helvetica","Arial","Verdana","sans-serif";

    font-size: 14px;

}

input, textarea{

    font-family: "Malgun Gothic","돋움","Trebuchet MS","Helvetica","Arial","Verdana","sans-serif";

    font-size: 12px;

}

table {

    border-collapse: collapse;

}

table,td,th {

    border: 1px solid black;

}

</style>

<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.7.2.min.js" charset="utf-8"></script>

<script type="text/javascript" charset="utf-8">

$(document).ready(function(){

       

        $("#addHandler").click(function(){

               $("form")

               .attr("method","post")

               .attr("action","<c:url value='/test/add.do'/>")

               .submit();                   

        });    

       

        $("#deleteHandler").click(function(){

               $("input[name=seq]").val($(this).attr("seq"));

               $("form")

               .attr("method","post")

               .attr("action","<c:url value='/test/remove.do'/>")

               .submit();                   

        });    

       

});

</script>

</head>

<body>

<form name="form1">

<input type="hidden" name="seq" />

<h2>ADD</h2>

<div>

memo : <input type="text" name="memo" />

<input type="button" value="DO ADD" id="addHandler" />

</div>

<hr/>

<h2>LIST</h2>

<table>

        <tr>

               <th>SEQ</th>

               <th>MEMO</th>

               <th>DATE</th>

               <th>ACTION</th>

        </tr>

        <c:forEach items="${data}" var="result" varStatus="i">

               <tr>

                       <td>${result.seq}</td>

                       <td>${result.memo}</td>

                       <td>${result.reg}</td>

                       <td><input type="button" value="DO DELETE" id="deleteHandler" seq="${result.seq}" /></td>

               </tr>

        </c:forEach>

</table>

</form>

</body>

</html>


Controller클래스는 아래와 같습니다. 아마도 실제로 사용하게 되면 service클래스를 생성하여 비지니스 로직을 처리해야 될것 같지만, 테스트이기때문에  service 클래스는 구현안했습니다.

TestController.java

package com.tistory.aircook.test;

 

import java.util.HashMap;

 

import java.util.Map;

 

import javax.servlet.http.HttpServletRequest;

 

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.HttpEntity;

import org.springframework.http.HttpHeaders;

import org.springframework.http.HttpMethod;

import org.springframework.http.MediaType;

import org.springframework.http.ResponseEntity;

import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;

import org.springframework.web.bind.ServletRequestUtils;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.client.RestTemplate;

 

/**

 * MemoController

 * @author francis Lee

 * @since 2012. 07. 10.

 */

@Controller

public class TestController {

 

        private final Log logger = LogFactory.getLog(getClass());

 

        @Autowired

        private RestTemplate restTemplate;

 

        @RequestMapping("/test/list.do")

        public String list(HttpServletRequest request, ModelMap model) throws Exception {

               if (logger.isDebugEnabled()) {

                       logger.debug("/test/list.do");

               }

               Map result = restTemplate.getForObject("http://localhost:8080/restservice/memos", Map.class);

               if (logger.isDebugEnabled()) {

                       logger.debug(result);

               }

               model.put("data", result.get("data"));

               return "/test/list";

        }

 

        @RequestMapping("/test/add.do")

        public String add(HttpServletRequest request, ModelMap model) throws Exception {

               if (logger.isDebugEnabled()) {

                       logger.debug("/test/add.do");

               }

               String memo = ServletRequestUtils.getStringParameter(request, "memo");

               Map params = new HashMap();

               params.put("memo", memo);

               Map result = restTemplate.postForObject("http://localhost:8080/restservice/memos", params, Map.class);

               if (logger.isDebugEnabled()) {

                       logger.debug(result);

               }

               return "redirect:/test/list.do";

        }

 

        @RequestMapping("/test/remove.do")

        public String remove(HttpServletRequest request, ModelMap model) throws Exception {

               if (logger.isDebugEnabled()) {

                       logger.debug("/test/remove.do");

               }

               String seq = ServletRequestUtils.getStringParameter(request, "seq");

               Map params = new HashMap();

               params.put("seq", seq);

              

               //restTemplate.delete("http://localhost:8080/restservice/memos/{seq}",params);

               // restTemplate.delete() 메소드는 결과값을 받을수 없다. exchange() 메소드를 사용하면?

               HttpHeaders headers = new HttpHeaders();

               headers.setContentType(MediaType.APPLICATION_JSON);

               HttpEntity<Map> entity = new HttpEntity<Map>(params, headers);

               ResponseEntity<Map> response = restTemplate.exchange("http://localhost:8080/restservice/memos/{seq}", HttpMethod.DELETE, entity, Map.class, params);

               Map result = response.getBody();

               if (logger.isDebugEnabled()) {

                       logger.debug(result);

               }

               return "redirect:/test/list.do";

        }

}