RESTful API Client 구현
[ 구현 목표 ]
- Java(Servlet/Spring)과 JSP를 이용해서 간단한 목록 보기 웹 브라우저 페이지를 만든다.
- JavaScript(Ajax)와 JSP를 이용해서 간단한 목록 보기 자바스크립트 중심의 웹 브라우저 페이지(원 페이지: 여러가지 업무를 하나의 페이지에서 한다.)를 만든다.
- 위 두개의 페이지를 RESTful API를 사용해서 만들어보고 각 특성을 확인해보자. (RESTful API는 ajax와 같이 많이 쓰인다. )
[ 초기 설정 ]
- 각 설정은 어제와 동일하며 기존 컨트롤러(RestContoller)를 사용하고, jsp파일만 따로 생성한다.
views > page.jsp (java,spring,servlet 기반의 일반적인 웹 페이지)
> spa.jsp (javascript, ajax 기반의 웹 페이지)
[ RestContoller.java ]
- 컨트롤러에서는 Java(Spring/Servlet) 일반적인 웹 페이지를 구현하는 코드와 바로 JavaScript가 있는 jsp로 연결하는 spa(원페이지)를 구현하는 코드 2가지가 있다.
@RequestMapping(value = "/page.action", method = { RequestMethod.GET })
public String page(HttpServletRequest req, HttpServletResponse resp, HttpSession session) throws Exception {
// 할일!!
// 데이터 수급 역할
// 1. DAO + DB 직접 조작
// 2. DAO + RESTful
// RESTful API 접근방법
URL url = new URL("http://localhost:8090/rest/color");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
// 돌려받은 JSON 형식의 문자열 > 실제 JSON 형식으로 변환 > JSONArray & JSONObject
// JSON 형식의 문자열을 JSON 관련 객체로 변환
JSONParser parser = new JSONParser();
JSONArray list = (JSONArray)parser.parse(reader); // ==> List<ColorDTO>와 비슷한 개념
reader.close();
// JSONArray를 바로 view에 넘긴다.
req.setAttribute("list", list);
}
return "page";
}
@RequestMapping(value = "/spa.action", method = { RequestMethod.GET })
public String spa(HttpServletRequest req, HttpServletResponse resp, HttpSession session) {
return "spa";
}
[ page.jsp ]
- 컨트롤러에서 받은 list를 forEach를 통해 데이터 값을 가져온다.
- 일반적인 웹 페이지 방식에는 목록을 보는 기능만 구현을 해두었다.
<h1 class="page-header">일반적인 웹 페이지 방식</h1>
<table class="table table-bordered">
<tr>
<th>번호</th>
<th>이름</th>
<th>코드</th>
<th>예시</th>
</tr>
<c:forEach items="${ list }" var="dto">
<tr>
<td>${ dto.seq }</td>
<td>${ dto.name }</td>
<td>${ dto.rgb }</td>
<td>${ dto.example }</td>
</tr>
</c:forEach>
</table>
[ spa.jsp ]
- SPA 페이지 방식(1장의 페이지에서 대부분의 업무를 처리)에서는 목록 보기, 추가, 삭제를 구현했다.
1) HTML
<h1 class="page-header">SPA 페이지 방식(한장의 페이지에서 대부분의 업무를 처리)</h1>
<table class="table table-bordered list">
<thead>
<tr>
<th>번호</th>
<th>이름</th>
<th>코드</th>
<th>예시</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div>
<form id="form1">
<table class="table table-bordered">
<tr>
<td><input type="text" name="name" class="form-control" /></td>
<td><input type="color" name="rgb" class="form-control" /></td>
<td><input type="text" name="example" class="form-control" /></td>
<td><button type="button" id="btnAdd" class="btn btn-default">추가하기</button></td>
</tr>
</table>
</form>
</div>
2) script
- 자바스크립트 객체를 JSON 표현의 문자열로 변경하기 위해 jQuery에서 지원하는 serializeObject가 필요한데 직접 다운 받아 script src로 경로를 추가해주었다. ( 다운로드 경로: https://plugins.jquery.com/serializeObject/ )
- 목록 삭제는 해당 표에서 이름을 클릭하면 삭제가 되도록 구현했다.
- 기존 ajax 와 달리 처음 사용해보는 부분은 contentType 부분이다. 기존 dataType과 비슷해 보이지만 다른점은 dataType은 받는 데이터 형식이며 contentType은 보내는 데이터 형식을 의미한다.
<script src="/rest/resources/js/jquery.serializeObject.js"></script>
<script>
// 해당 목록 삭제 하기
function del() {
let td = event.srcElement;
let seq = $(td).parent().children().eq(0).text();
$.ajax({
type: 'DELETE',
url: 'http://localhost:8090/rest/color/' + seq,
dataType: 'json',
success: function(result) {
if(result == 1) {
$(td).parent().remove();
}
else {}
},
error: function(a, b, c) {
console.log(a, b, c);
}
});
}
// 시작 > 데이터 가져오기
$.ajax({
type: 'GET',
url: 'http://localhost:8090/rest/color',
dataType: 'json',
success: function(list) {
$(list).each(function(index, item) {
$('.list tbody').append('<tr><td>' + item.seq + '</td><td onclick="del();">'+ item.name +'</td><td>' + item.rgb + '</td><td>' + item.example + '</td></tr>');
});
},
error: function(a, b, c) {
console.log(a, b, c);
}
});
// 클릭 이벤트 (데이터 추가하기)
$('#btnAdd').click(function() {
// 자바 스크립트 객체 > JSON 표현의 문자열로 변경
let data = JSON.stringify($('#form1').serializeObject());
$.ajax({
type: 'POST',
url: 'http://localhost:8090/rest/color',
dataType: 'json', // 받는 데이터 형식
data: data, // 보내는 데이터
contentType: 'application/json;charset=UTF-8',
success: function(result) {
if(result == 1) {}
else {}
},
error: function(a, b, c) {
console.log(a, b, c);
}
});
}
</script>
[ 결과 페이지 ]
1) page.jsp
2) spa.jsp
MEMO>
# 아직 RESTful API에 대해 잘 몰라서 그런지 어떻게, 왜 쓰이는지는 아직 잘 모르겠다.
# 수업해주는 RESTful API는 극히 기본적인 부분이며 배워야할 부분이 많이 존재한다.
# 처음 ajax코드는 생소해서 오타가 많이 발생했는데, 일주일 정도 ajax 코드를 작성하다보니 나름 익숙해진것 같다!!
'교육 > Spring' 카테고리의 다른 글
Spring 개발자 수업 110일차(2) - RESTful API (0) | 2021.09.02 |
---|---|
Spring 개발자 수업 110일차(1) - RESTful API (0) | 2021.09.02 |
Spring 개발자 수업 109일차 - jQuery Ajax를 이용한 post-it 메모장 만들기(작성, 위치 저장, 삭제) (0) | 2021.08.31 |
Spring 개발자 수업 108일차 - jQuery Ajax를 이용한 post-it 메모장 만들기(생성, 확인) (0) | 2021.08.30 |
Spring 개발자 수업 107일차 - 휴강 (0) | 2021.08.28 |
댓글