JSON과 GSON
Ajax의 경우 서블릿에서 여러개의 응답 데이터를 담는것이 어렵다.
이때 활용할 수 있는 JSON에 대해 알아보고
JSON을 더 쉽게 사용할수 있도록 도와주는 GSON에 대해서도 알아보자.
JSON 이란?
- JavaScript Object Notation : 자바스크립트 객체 표기법
- ajax 통신 시 데이터 전송에 자주 사용되는 포맷형식 중 하나
서블릿에서 여러개의 데이터를 담을때 활용한다. - JSON 라이브러리 설치하기
1) https://code.google.com/archive/p/json-simple/downloads
2) [ json-simple-1.1.1.jar ] 다운받기
3) WEB-INF/lib 폴더에 붙여넣기
JSON 사용하기
- response.setContentType("application/json; charSet=UTF-8")
JSON으로 응답시에 먼저 content type을 설정해주어야한다. - JSONArray 객체
- [value, value2, ... ] 형태
>>자바스크립트에서의 배열객체
- 순번으로 데이터에 접근한다
- new JSONArray()으로 객체 생성 후 객체.add(값) 으로 데이터 담는다.
>> 0번부터 순차적으로 담긴다. - JSONObject 객체
- {key:value, key2:value2, ...} 형태
>> 자바스크립트에서의 일반객체
- 키값으로 데이터에 접근한다.
- key는 반드시 문자열 사용하며, value는 String, Number, Boolean, Array, Object, null 저장 가능
(char타입은 오류가 난다 1글자여도 String타입을 쓰도록 한다)
- new JSONObject()로 객체 생성 후 객체.put("키", 밸류) 으로 데이터 담는다
GSON 이란?
- Google JSON의 약자로 Google에서 만든 오픈 라이브러리
- JSON파일을 쉽게 읽고 만들 수 있는 메소드 제공
- Gson객체.toJson(Object, Appendable)
>> 매개변수 Object를 JSON으로 변환해서 Appendable에 연결된 출력스트림으로 출력한다.
(vo객체는 JSONObject, 자바배열 또는 ArrayList는 JSONArray로 변환됨.) - JSONObject의 key는 해당 vo객체의 필드명으로 설정되며,
이때 속성값이 있는 필드만 정의해준다(null은 속성으로 정의하지 않음) - 라이브러리 설치 방법
https://mvnrepository.com/에 접속해서 gson검색
>>버전은 사용자(Usages)가 많은 버전을 클릭한다(2.8.5)
>>Files에 있는 jar 클릭하여 다운로드
>>WEB-INF/lib 폴더에 붙여넣기
실습1 : JSON 사용
JSONArray와 JSONObject를 사용하여 데이터를 주고받고 활용하는 연습을 하자
1-1) 화면딴 : JSONArray로 데이터 넘겨받기
- JSONArray로 데이터를 넘겨받았다면 인덱스로 접근할 수 있다.
이름 : <input type="text" id="input2_1"> <br>
나이 : <input type="number" id="input2_2"> <br>
<button id="btn2">전송</button> <br>
응답 : <ul id="output2"></ul>
<script>
$(function(){
$('#btn2').click(function(){
$.ajax({
url:"/web/test2.do",
data:{
name:$('#input2_1').val(),
age:$('#input2_2').val()
},
type:"post",
success:function(a){
//방법1. JSONArray의 경우 배열로 출력되는것 확인할 수 있다.
console.log(a);
//데이터에는 순번으로 접근
console.log(a[0]);
console.log(a[1]);
},
.....
1-2) 서블릿 : JSONArray로 데이터 넘기기
- 서블릿/test2.do
- JSONArray를 사용하여 데이터를 담아서 보내기
>>이때 add 메소드 사용
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
//빈문자열이나 null을 파싱하면 에러 남(NumberFormatException).
int age = Integer.parseInt(request.getParameter("age"));
//자바스크립트의 배열형태인 JSONArray에 담아보자
JSONArray jArr = new JSONArray(); // [] 텅빈배열
jArr.add(name); // 0번인덱스에 담긴다
jArr.add(age); // 1번인덱스에 담긴다
//응답데이터가 JSON형태일때 해당 마임타입을 입력해야한다
response.setContentType("application/json; charSet=UTF-8");
response.getWriter().print(jArr);
}
2-1) 화면딴 : JSONObject로 데이터 넘겨받기
- JSONObject를 사용하는 경우 속성으로 데이터에 접근할 수 있다.
- ul태그 안에 li태그를 만들어 데이터를 출력해본다.
<script>
$.ajax({
.....
success:function(a){
console.log(a);
console.log(a.name);
console.log(a.age);
const value = "<li>"+a.name+"</li>"
+"<li>"+a.age+"</li>";
$('#output2').html(value);
},
.....
</script>
2-2) 서블릿 : JSONObject로 데이터 넘기기
- JSONObject 객체를 사용해서 데이터를 담는다.
>> put("키", 밸류) 메소드 사용
.....
//방법2. 자바스크립트의 일반객체형태
JSONObject jObj = new JSONObject();
jObj.put("name", name);
jObj.put("age", age);
response.setContentType("application/json; charSet=UTF-8");
response.getWriter().print(jObj);
}
실습2 : GSON 사용
검색어를 서버에서 조회해보고, 조회된 vo객체를 응답데이터로 화면에 출력해보자
이 과정을 JSON만을 이용해서 처리해보고
이때 GSON하면 코드가 얼마나 간결해지는지 비교해보자
1) 화면설계하기
- 아이디를 검색하는 구조를 짜본다.
검색하고자하는 회원 아이디 : <input type="text" id="input3">
<button onclick="test3();">검색</button>
<div id="output3">검색결과영역</div>
<script>
function test3(){
$.ajax({
url:"/web/test3.do",
data:{id:$("#input3").val()},
success:function(result){
console.log(result);
if(result == null){
$('#output3').html("검색결과가 없습니다.");
}else{
const value = "회원번호: "+result.userNo+"<br>"
+ "회원아이디: "+result.userId+"<br>"
+ "이름: "+result.userName+"<br>";
$('#output3').html(value);
}
},
error:function(){
console.log('ajax통신실패')
}
})
}
<script>
2-1) Ajax용 서블릿 만들기
- vo 클래스 객체인 Member m을 기존방식처럼 넘기면, 화면딴에서 출력해봤을때 필드의 정보가 toString메소드로 문자열로 연이어져 있음을 확인할 수 있다.
>> toString이 자동으로 붙어 문자열이 넘어갔다!!
>>JSON을 사용해야하는이유
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userId = request.getParameter("id");
Member m = new MemberDao().selectMember(JDBCTemplate.getConnection(),userId);
//Member객체 각 필드에 조회된 데이터들이 담겨있을것.
//response.getWriter().print(m/*.toString*/);
//자바에서의 객체를 곧바로 응답시 .toString()의 문자열이 응답됨
//JSONObject에 직접 담기
JSONObject jObj = new JSONObject();
jObj.put("userNo", m.getUserNo());
jObj.put("userName", m.getUserName());
jObj.put("userId", m.getUserId());
response.setContentType("application/json; charset=UTF-8");
response.getWriter().print(jObj);
}
2-2)위 과정을 Gson으로 한줄로 정리하기
- 위 과정과 다르게 3가지 필드가 아닌 모든 필드가 담겨서 넘어간다.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userId = request.getParameter("id");
Member m = new MemberDao().selectMember(JDBCTemplate.getConnection(),userId);
response.setContentType("application/json; charset=UTF-8");
new Gson().toJson(m, response.getWriter());
}
JSONArray에 담긴 JSONObject, 그리고 GSON
공지사항테이블에 있는 데이터들을 조회해서
화면에 목록을 뿌려보자.
이때 조회결과는 vo객체가 담겨있는 ArrayList이다.
1) 화면딴 구조짜기
- 공지사항 목록을 뿌릴 위치를 만들고 Ajax를 호출한다.
<button onclick="test4();">공지사항 전체조회</button>
<table id="output4" border="1">
<thead>
<tr>
<th>번호</th>
<th>제목</th>
<th>작성자</th>
<th>조회수</th>
</tr>
</thead>
<tbody>
<!-- 데이터가 뿌려질 곳 -->
</tbody>
</table>
<script>
function test4(){
$.ajax({
url:"/web/test4.do",
success:function(){
},
error:function(){
console.log('ajax 통신실패')
}
})
}
</script>
2) 서블릿 작성하기
- 조회된 객체는 vo객체들이 담긴 ArrayList이다.
>> 해당 객체를 toJson() 메소드에 태우면 자동으로 큰 골격은 JSONArray,
담겨있는 객체들은 JSONObject로 바꿔준다.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ArrayList<Notice> list = new NoticeService().selectNoticeList();
// JSONArray로 넘겨주어야함. 이때 담겨있는 vo객체는 자바스크립트 객체로 만든다
// [{Notice객체},{Notice객체},...] => JSONObject로 담은 후 JSONArray에 담기
// Gson이 알아서 해준다.
response.setContentType("application/json; charset=UTF-8");
new Gson().toJson(list, response.getWriter());
}
3) 데이터 뿌리기
- 전달받은 데이터를 콘솔에 출력해보면 배열안에 객체가 담겨있다는 것을 확인할 수 있다.
>> 순번으로 객체에 순차적으로 접근한 후 속성(필드명)으로 담겨있는 데이터를 꺼낸다
<script>
.....
success:function(result){
console.log(result); // 배열 안에 객체 담겨있음 확인
let value = "";
for(let i=0; i<result.length; i++) {
value += "<tr>"
+"<td>"+result[i].noticeNo+"</td>"
+"<td>"+result[i].noticeTitle+"</td>"
+"<td>"+result[i].noticeWriter+"</td>"
+"<td>"+result[i].count+"</td>"
+"</tr>"
}
$('#output4 tbody').html(value);
},
.....
</script>

'다양한 기술들 > Web 관련' 카테고리의 다른 글
| [06] JSP 응용 : 표준액션태그 (0) | 2023.02.09 |
|---|---|
| [05] JSP 응용 : EL (0) | 2023.02.09 |
| [03] Ajax 기초, 실습 (0) | 2023.01.18 |
| [JSP] 간단한 실습 (0) | 2023.01.10 |
| [JSP] HTML 위에서 작성하는 Java / 기본 문법 (0) | 2023.01.10 |
댓글