Java objects to XML using JAXB (Servlet)

Programming/Java 2014/12/04 10:41 Posted by 파란크리스마스

출처 : JAXB(위키백과)
@XMLAccessorType, @XMLRootElement
JAXB 2.0 Annotation 정리
How to customise an XML export using JAXB
Creating a Generic List Wrapper in JAXB

JAXB(Java Architecture for XML Binding)는 자바 클래스를 XML로 표현하는 자바 API이다. JAXB는 주로 2가지 기능이 있다. 자바 객체를 XML로 직렬화하는 것이고 반대로 XML에서 자바 객체로 역직렬화하는 것이다. 즉, JAXB는 메모리의 데이터를 XML 형식으로 변환하여 저장할 수 있고, 이 과정을 위해 프로그램의 각 클래스에서 XML을 읽고 저장하는 일을 구현해야 한다.

JAXB 2.0 Annotation 정리

@XmlRootElement 속성

  • name : xml root element 명 지정
  • namespace: namespace 지정

@XmlAccessorType의 설정

@XmlAccessorType(XmlAccessType.PROPERTY)

  • 모든 getter/setter 쌍을 JAXB 직렬화/역직렬화 대상으로 함
  • JAXB 직력화/역직력화에서 제외하고자 할 경우 getter 혹은 setter에 @XmlTransient를 사용
  • @XmlTransient는 getter/setter 상단에 설정
    • 멤버변수 상단에 설정시 적용 않됨
  • getter/setter가 존재하지 않는 public 멤버 변수를 JAXB 직력화/역직력화에서 추가하고자 할 경우 JAXB 어노테이션 사용
    • @XmlElement
    • @XmlAttribute

Employee

package com.test;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name = "Emp")
@XmlType(propOrder = {"name", "age", "role", "gender"})
public class Employee {

	private int id;

	private String gender;

	private int age;
	private String name;
	private String role;

	private String password;

	@XmlTransient
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@XmlAttribute
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@XmlElement(name = "gen")
	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
	}

	@Override
	public String toString() {
		return "ID = " + id + " NAME=" + name + " AGE=" + age + " GENDER="
				+ gender + " ROLE=" + role + " PASSWORD=" + password;
	}

}

JAXBExample

package com.test;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class JAXBExample {

	private static final String FILE_NAME = "jaxb-emp.xml";

	public static void main(String[] args) {
		Employee emp = new Employee();
		emp.setId(1);
		emp.setAge(25);
		emp.setName("Pankaj");
		emp.setGender("Male");
		emp.setRole("Developer");
		emp.setPassword("sensitive");

		jaxbObjectToXML(emp);

		Employee empFromFile = jaxbXMLToObject();
		System.out.println(empFromFile.toString());
	}

	private static Employee jaxbXMLToObject() {
		try {
			JAXBContext context = JAXBContext.newInstance(Employee.class);
			Unmarshaller un = context.createUnmarshaller();
			Employee emp = (Employee) un.unmarshal(new File(FILE_NAME));
			return emp;
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		return null;
	}

	private static void jaxbObjectToXML(Employee emp) {

		try {
			JAXBContext context = JAXBContext.newInstance(Employee.class);
			Marshaller m = context.createMarshaller();
			// for pretty-print XML in JAXB
			m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

			// Write to System.out for debugging
			// m.marshal(emp, System.out);

			// Write to File
			m.marshal(emp, new File(FILE_NAME));
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}

}

결과 파일 : jaxb-emp.xml

JAXBExample에서 Employee 클래스에 데이터를 담고, 그것을 xml로 출력한 결과입니다.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Emp id="1">
    <name>Pankaj</name>
    <age>25</age>
    <role>Developer</role>
    <gen>Male</gen>
</Emp>

Wrapper

package com.test;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAnyElement;

public class Wrapper<T> {
	private List<T> items;

	public Wrapper() {
		items = new ArrayList<T>();
	}

	public Wrapper(List<T> items) {
		this.items = items;
	}

	@XmlAnyElement(lax = true)
	public List<T> getItems() {
		return items;
	}
}

XMLServlet

package com.test;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.namespace.QName;
import javax.xml.transform.stream.StreamSource;

@WebServlet(urlPatterns = "/xml")
public class XMLServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/xml;charset=UTF-8");
		OutputStream out = resp.getOutputStream();

		try {
			JAXBContext jc = JAXBContext.newInstance(Wrapper.class, Employee.class);
			
			// Marshal
			Marshaller marshaller;
			
			marshaller = jc.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshal(marshaller, getEmpDatas(), "emps", out);

		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		out.close();
	}

	/** * Unmarshal XML to Wrapper and return List value. */
	private static <T> List<T> unmarshal(Unmarshaller unmarshaller, Class<T> clazz, String xmlLocation) throws JAXBException {
		StreamSource xml = new StreamSource(xmlLocation);
		Wrapper<T> wrapper = (Wrapper<T>) unmarshaller.unmarshal(xml, Wrapper.class).getValue();
		return wrapper.getItems();
	}

	/**
	 * * Wrap List in Wrapper, then leverage JAXBElement to supply root element *
	 * information.
	 */
	private static void marshal(Marshaller marshaller, List<?> list, String name, OutputStream os) throws JAXBException {
		QName qName = new QName(name);
		Wrapper wrapper = new Wrapper(list);
		JAXBElement<Wrapper> jaxbElement = new JAXBElement<Wrapper>(qName, Wrapper.class, wrapper);
		marshaller.marshal(jaxbElement, os);
	}

	private List<Employee> getEmpDatas() {

		List<Employee> datas = new ArrayList<Employee>();

		Employee emp = new Employee();
		emp.setId(1);
		emp.setAge(25);
		emp.setName("Pankaj");
		emp.setGender("Male");
		emp.setRole("Developer");
		emp.setPassword("sensitive");

		datas.add(emp);

		emp = new Employee();
		emp.setId(11);
		emp.setAge(125);
		emp.setName("1Pankaj");
		emp.setGender("1Male");
		emp.setRole("1Developer");
		emp.setPassword("1sensitive");

		datas.add(emp);

		return datas;
	}
}

실행결과

소스파일

ObjToXML.zip



 

티스토리 툴바