어떤 플랫폼에 상관없이 공통적으로 사용할 수 있는 데이터는 xml , JSON 이다
여기서는 xml 형식의 데이터 사용 방법을 알아보자
1.스프링에서 데이터를 xml 형식으로 가공 한다.
2.안드로이드에서 가공한 xml 을 parse 해서 보여준다.
스프링 에서 xml 데이터 가공하기
쿼리 - mysql
create table book (
book_code Integer AUTO_INCREMENT primary key,
book_name varchar(50) not null,
press varchar(50) not null,
price Integer default 0,
amount Integer default 0
);
insert into book values ( null, 'java', '삼양', 30000, 10);
insert into book values (null, 'jsp', '영진', 35000, 20);
insert into book values ( null,'spring', '길벗', 25000, 30);
insert into book values (null, 'oracle', '한빛', 20000, 15);
insert into book values (null, 'android', '가메', 40000, 25);
pom.xml
<!-- 안드로이드 연동 xml - json -->
<!-- https://mvnrepository.com/artifact/org.jdom/jdom -->
<!-- xml 생성 -->
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom</artifactId>
<version>2.0.2</version>
</dependency>
<!-- 구글 JSON 라이브러리 -->
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<!-- <dependency> 상단에 추가 json 객체 생성
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
-->
<!-- jackson-databind는 상단에 추가 하였음 -->
<!-- jackson-databind 는 @ResponseBody json 타입으로 리턴하기 위한것 -->
class BookVO
public class BookVO {
private int book_code;
private String book_name;
private String press;
private int price;
private int amount;
//geter, seter, toString()
}
interface BookDAO
package com.macaronics.www.sample.dao;
import java.util.List;
import com.macaronics.www.sample.dto.BookVO;
public interface BookDAO {
public List<BookVO> bookList();
}
bookMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 다른 mapper와 중복되지 않도록 네임스페이스 기재 -->
<mapper namespace="MYSQL.bookMapper">
<select id="bookList" resultType="com.macaronics.www.sample.dto.BookVO">
select * from book order by book_name asc
</select>
</mapper>
class BookDAOImpl
package com.macaronics.www.sample.dao;
import java.util.List;
import javax.inject.Inject;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;
import com.macaronics.www.SqlServerEnvironment;
import com.macaronics.www.sample.dto.BookVO;
@Repository
public class BookDAOImpl implements BookDAO {
@Inject
private SqlSession sqlSession;
private final String namespace=SqlServerEnvironment.SQL+".bookMapper";
@Override
public List<BookVO> bookList() {
return sqlSession.selectList(namespace+".bookList");
}
}
interface BookService
package com.macaronics.www.sample.service;
import java.util.List;
import com.macaronics.www.sample.dto.BookVO;
public interface BookService {
public List bookList();
}
class BookServiceImpl
package com.macaronics.www.sample.service;
import java.util.List;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
import com.macaronics.www.sample.dao.BookDAO;
import com.macaronics.www.sample.dto.BookVO;
@Service
public class BookServiceImpl implements BookService {
@Inject
private BookDAO bookDAO;
@Override
public List bookList() {
return bookDAO.bookList();
}
}
class BookController
package com.macaronics.www.sample.Controller;
import java.util.List;
import javax.inject.Inject;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.macaronics.www.sample.dto.BookVO;
import com.macaronics.www.sample.service.BookService;
@Controller
public class BookController {
@Inject
private BookService bookService;
private final static Logger logger=LoggerFactory.getLogger(BookController.class);
//리스트를 xml 로 만들어서 json 형식으로 리턴
// jdom (xml 생성기) , json 라이브러리 pom.xml 에 추가
// mavenRepository => org.jdom 2.0.2 추가
// json-simple => 1.1.1 버전 추가
// jackson-databind
@ResponseBody //리턴 자료형을 xml or json
@RequestMapping(value="/xml.do", produces="application/json; charset=utf-8")
public String xml(){
List list=bookService.bookList();
//org.jdom2
//Element : xml 노드(태그)
// root 노드
Element root =new Element("books");
// xml 문서객체
Document doc =new Document(root);
// xml 문서에 root 노드 설정
// detach() 새로운 문서를 만들기 전에 클리어 시킴
//root 를 초기화 시키면서 doc에 붙인다
doc.setRootElement(root.detach());
String result="";
for(BookVO vo : list){
// 태그
Element book =new Element("book");
Element book_code=new Element("book_code");
//텍스트
//숫자 +"=>숫자를 문자열로
book_code.setText(vo.getBook_code()+"");
Element book_name=new Element("book_name");
book_name.setText(vo.getBook_name());
Element press =new Element("press");
press.setText(vo.getPress());
Element price=new Element("price");
price.setText(vo.getPrice()+"");
Element amount=new Element("amount");
amount.setText(vo.getAmount()+"");
book.addContent(book_code);
book.addContent(book_name);
book.addContent(press);
book.addContent(price);
book.addContent(amount);
root.addContent(book);
}
//Document 타입을 스트링으로 변환
//org.jdom2
//xml 출력을 위한 객체
XMLOutputter xout =new XMLOutputter();
Format f=xout.getFormat();//xml 문서의 포맷 설정
f.setEncoding("utf-8"); //인코딩 방식 설정
f.setIndent("\t");//들여쓰기 문자
f.setLineSeparator("\r\n"); //줄바꿈 문자
f.setTextMode(Format.TextMode.TRIM); //공백제거
xout.setFormat(f);//문서 포맷 적용
//Document 를 스트링으로 변환
result=xout.outputString(doc);
return result;
}
}
안드로이드 xml Parse
class BookVO
public class BookVO {
private int book_code;
private String book_name;
private String press;
private int price;
private int amount;
public int getBook_code() {
return book_code;
}
public void setBook_code(int book_code) {
this.book_code = book_code;
}
public String getBook_name() {
return book_name;
}
public void setBook_name(String book_name) {
this.book_name = book_name;
}
public String getPress() {
return press;
}
public void setPress(String press) {
this.press = press;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
@Override
public String toString() {
return "BookVO{" +
"book_code=" + book_code +
", book_name='" + book_name + '\'' +
", press='" + press + '\'' +
", price=" + price +
", amount=" + amount +
'}';
}
}
class XmlActivity
package com.example.choi.ex05_network;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.example.choi.ex05_network.dto.BookVO;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class XmlActivity extends AppCompatActivity
implements Runnable{
//1.변수 선언
ListView list1;
List items;
final String url_Address="http://192.168.0.2:2002/xml.do";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xml);
//2.위젯 연결
list1 =(ListView)findViewById(R.id.list1);
items=new ArrayList<>();
//3.스레드 객체 생성
Thread th =new Thread(this);
th.start();
}
@Override
public void run() {
//네트워크 접속, xml 리턴
try{
URL url=new URL(url_Address);
// xml 분석기 객체 생성
XmlPullParser parser=
XmlPullParserFactory.newInstance().newPullParser();
InputStream is =url.openStream();//스트림 생성
//xml 분석기에 스트림을 입력
parser.setInput(is, "utf-8");
//xml 문서의 이벤트 (태그의 시작, 끝 등)
int eventType=parser.getEventType();
String tag;
BookVO vo=new BookVO();
//xml 분석 시작
while (eventType !=XmlPullParser.END_DOCUMENT){
switch (eventType){
case XmlPullParser.START_TAG://시작 태그
tag=parser.getName();//태그 이름
if(tag.equals("book_code")){
vo=new BookVO();
vo.setBook_code(Integer.parseInt(parser.nextText()));
}
if(tag.equals("book_name")){
//자바
//parser.nextText() 는 시작 태그의 다음인 자바 글자를 가져온다
vo.setBook_name(parser.nextText());
}
if(tag.equals("press")){
vo.setPress(parser.nextText());
}
if(tag.equals("price")){
vo.setPrice(Integer.parseInt(parser.nextText()));
}
if(tag.equals("amount")){
vo.setAmount(Integer.parseInt(parser.nextText()));
}
break;
case XmlPullParser.END_TAG:
tag=parser.getName();
if(tag.equals("book")){
items.add(vo);
vo=null;
}
break;
}
eventType =parser.next();//다음으로 이동 여기서 다음 book 태그로 이동
}
}catch (Exception e){
e.printStackTrace();
}
//핸들러에게 메시지 호출(리스트뷰 갱신)
//handleMessage() 가 호출됨;
handler.sendEmptyMessage(1);
}
//android.os
Handler handler=new Handler(){
//Alt+Enter , Override Methods
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//리스트뷰 출력
String[] books =new String[items.size()];
for(int i=0; i adapter=
new ArrayAdapter(XmlActivity.this,
android.R.layout.simple_list_item_1, books);
list1.setAdapter(adapter);
}
};
}
activity_xml.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_xml"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.choi.ex05_network.XmlActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:id="@+id/list1" />
</RelativeLayout>
댓글 ( 4)
댓글 남기기