1. Jackson-Databind
: Jackson은 자바용 Data-Processing 툴로서 Json 뿐만 아니라 XML/YAML/CSV 등 다양한 형식의 데이터를 지원한다,
스트림 방식이므로 속도가 빠르며 유연하며 다양한 third party 데이타 타입을 지원하며
annotation 방식으로 메타 데이터를 기술할 수 있으므로 JSON의 약점중 하나인 문서화와
데이터 validation 문제를 해결할 수 있다.
[사용하는 방법] Maven 설정, Gradle 설정, 라이브러리 다운로드
2. 라이브러리 다운 받기(jackson-dataformat-xml, jackson-module-jaxb-annotations, woodstox-core, stax2-api)
: mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-xml > 2.10.2 버전 선택
> Jackson Dataformat XML 다운
> jackson-core, jackson-annotations, jackson-databind, jackson-module-jaxb-annotations, woodstox-core, stax2-api
모두 다운 받아야 함
> 현재 jackson-core, jackson-annotations, jackson-databind들은 다운 받은 상태이기 때문에
나머지 세 개만 다운 받으면 됨
> 다운받은 jar 파일들은 WebContent > WEB-INF > lib에 복사하기
3. Json response
: com.lec.beans > AjaxWriteListJson 클래스
package com.lec.beans;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
// POJO : Plain Old Java Object
public class AjaxWriteListJson {
int count; // 데이터 개수
String status; // 처리 결과
@JsonIgnore
String memo; // response에서 제외할 필드
@JsonProperty("data") // Json property 이름과 Java 필드명이 다른 경우
List<WriteDTO> list;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public List<WriteDTO> getList() {
return list;
}
public void setList(List<WriteDTO> list) {
this.list = list;
}
}
4. XML response
: com.lec.beans > AjaxWriteListXml 클래스
package com.lec.beans;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
@JacksonXmlRootElement(localName = "WriteList")
public class AjaxWriteListXml {
int count; // 데이터 개수
String status; // 처리 결과
@JsonIgnore
String memo; // response에서 제외할 필드
@JacksonXmlElementWrapper(useWrapping = false)
@JacksonXmlProperty(localName = "Data")
List<WriteDTO> list;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public List<WriteDTO> getList() {
return list;
}
public void setList(List<WriteDTO> list) {
this.list = list;
}
}
5. Ajax용 Command
: com.command.write > AjaxListCommand 서블릿
package com.command.write;
import java.io.IOException;
import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.json.JSONArray;
import org.json.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.lec.beans.AjaxWriteListJson;
import com.lec.beans.AjaxWriteListXml;
import com.lec.beans.WriteDTO;
public class AjaxListCommand implements Command {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
// parameter 받아오기, 없으면 json 동작 디폴트로
String reqType = request.getParameter("reqType");
if(reqType == null) {reqType = "json";}
// "xml" 혹은 "json"으로 response 하기
switch(reqType) {
case "xml":
//responseXML(request, response); // jdom 사용
responseXML2(request, response); // Jackson 사용
break;
default:
//responseJSON(request, response); // org.json 사용
responseJSON2(request, response); // Jackson 사용
} // end switch
} // end execute()
private void responseJSON(HttpServletRequest request, HttpServletResponse response) {
WriteDTO[] dtoArr = (WriteDTO[])request.getAttribute("list");
JSONObject jsonOutput = new JSONObject(); // 최종 결과는 object
if(dtoArr == null) {
jsonOutput.put("status", "FAIL");
} else {
jsonOutput.put("status", "OK"); // object에 property-value 추가
int count = dtoArr.length;
jsonOutput.put("count", count);
// 글 목록
JSONArray dataArr = new JSONArray(); // array
for(int i = 0; i < count; i++) {
JSONObject dataObj = new JSONObject();
dataObj.put("uid", dtoArr[i].getUid());
dataObj.put("name", dtoArr[i].getName());
dataObj.put("subject", dtoArr[i].getSubject());
dataObj.put("content", dtoArr[i].getContent());
dataObj.put("viewCnt", dtoArr[i].getViewCnt());
dataObj.put("regdate", dtoArr[i].getRegDate());
// array에 추가
dataArr.put(dataObj);
}
jsonOutput.put("data", dataArr);
}
String jsonString = jsonOutput.toString(); // JSON 객체 --> String 변환
response.setContentType("application/json; charset=utf-8"); // MIME 설정
try {
response.getWriter().write(jsonString); // response 내보내기
} catch (IOException e) {
e.printStackTrace();
}
} // end responseJSON()
private void responseJSON2(HttpServletRequest request, HttpServletResponse response) {
WriteDTO[] dtoArr = (WriteDTO[]) request.getAttribute("list");
AjaxWriteListJson list = new AjaxWriteListJson(); // response 할 Java 객체
ObjectMapper mapper = new ObjectMapper(); // JSON 으로 매핑할 Mapper 객체
if(dtoArr == null) {
list.setStatus("FAIL");
} else {
list.setStatus("OK");
list.setCount(dtoArr.length);
list.setList(Arrays.asList(dtoArr));
}
String jsonString;
try {
// Java객체 --> JSON 문자열로 변환
jsonString = mapper.writeValueAsString(list);
response.setContentType("application/json; charset=utf-8"); // MIME 설정
response.getWriter().write(jsonString); // response 보내기
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} // end responseJSON2()
private void responseXML(HttpServletRequest request, HttpServletResponse response) {
WriteDTO[] dtoArr = (WriteDTO[])request.getAttribute("list");
Document dom = new Document();
Element rootElement = new Element("WriteList"); // <WriteList>..</WriteList>
dom.setRootElement(rootElement);
Element statusElement = new Element("status");
if(dtoArr == null ) {
statusElement.setText("FAIL");
} else {
statusElement.setText("OK");
// 데이터 개수
int count = dtoArr.length;
Element countElement = new Element("Count")
.setText("" + count)
.setAttribute("id", "ccc")
.setAttribute("pw", "xxx")
;
rootElement.addContent(countElement);
// 데이터 끌어오기!
for(int i = 0; i < count; i++) {
Element dataElement = new Element("Data");
dataElement.addContent(new Element("uid").setText(dtoArr[i].getUid() + ""));
dataElement.addContent(new Element("name").setText(dtoArr[i].getName() + ""));
dataElement.addContent(new Element("subject").setText(dtoArr[i].getSubject() + ""));
dataElement.addContent(new Element("content").setText(dtoArr[i].getContent() + ""));
dataElement.addContent(new Element("viewCnt").setText(dtoArr[i].getViewCnt() + ""));
dataElement.addContent(new Element("regdate").setText(dtoArr[i].getRegDate() + ""));
rootElement.addContent(dataElement);
}
}
rootElement.addContent(statusElement);
// new XMLOutputter(Format.getPrettyFormat()) : 콘솔에서도 이쁘게 출력 가능함
XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
System.out.println(xmlOutputter.outputString(dom)); // 테스트용
try {
response.setContentType("application/xml; charset=utf-8"); // text/xml도 가능.
response.getWriter().write(xmlOutputter.outputString(dom));
} catch(IOException e) {
e.printStackTrace();
}
} // end responseXML()
private void responseXML2(HttpServletRequest request, HttpServletResponse response) {
WriteDTO[] dtoArr = (WriteDTO[])request.getAttribute("list");
AjaxWriteListXml list = new AjaxWriteListXml(); // response 할 Java 객체
if(dtoArr == null) {
list.setStatus("FAIL");
} else {
list.setStatus("OK");
list.setCount(dtoArr.length);
list.setList(Arrays.asList(dtoArr));
} // end if
XmlMapper mapper = new XmlMapper(); // XML 매핑할 Mapper 객체
try {
// Java --> XML 문자열로 변환
String xmlString = mapper.writeValueAsString(list);
response.setContentType("application/xml; charset=utf-8"); // MIME 설정
response.getWriter().write(xmlString);
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} // end responseXML2()
}
6. Java, API request-response 라이브러리
: Retrofit2, Volley(안드로이드)
'웹_프론트_백엔드 > JAVA프레임윅기반_풀스택' 카테고리의 다른 글
2020.06.01 (0) | 2020.06.01 |
---|---|
2020.05.28 (0) | 2020.05.28 |
2020.05.26 (0) | 2020.05.26 |
2020.05.25 (0) | 2020.05.25 |
2020.05.22 (0) | 2020.05.22 |