728x90
300x250
[Spring-Framework] 42. Spring Framework에서 (Jaxb-runtime, activation, Jaxb Api, JSTL)을 활용한 XML 생성하기


이번에 소개할 방법은 Spring Framework에서 Jaxb-runtime, activation, Jaxb Api, JSTL을 활용하여 XML을 생성하는 방법에 대해서 소개하겠다.


JSP/Servlet 방식하고는 차이가 있는 점이 있다면, @(어노테이션)을 사용할 것이다.


* IDE: Eclipse 2020-06
* Library: Maven Project / Spring Framework 4.2.4 Releases.

1. https://mvnrepository.com/artifact/javax.servlet/servlet-api

   javax.servlet 2.5

2. https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api

   jaxb-api 2.3.0-b170201.1204

3. https://mvnrepository.com/artifact/javax.activation/activation

   activation 1.1

4. https://mvnrepository.com/artifact/org.glassfish.jaxb/jaxb-runtime

   jaxb-runtime 2.3.0-b170127.1453

5. https://mvnrepository.com/artifact/javax.servlet/jstl

   jstl 1.2



1. 프로젝트 구성도


실제로는 코드가 몇 줄 되지는 않지만, 문제는 라이브러리 셋팅 등에서 오류를 많이 경험할 수 있다.



그림 1. 프로젝트 구성도




2. Java Compiler, Build Path, Project Factes


* Java Compiler - compiler compliance level 1.8
* Build Path -> JRE System Library 1.8
* Project Factes - Java : 1.8



3. pom.xml

이 셋팅이 매우 무척 많이 중요하다.


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.website</groupId>
 <artifactId>example</artifactId>
 <name>Spring-XML-Jaxb</name>
 <packaging>war</packaging>
 <version>1.0.0-BUILD-SNAPSHOT</version>
 <properties>
  <java-version>1.8</java-version>
  <org.springframework-version>4.2.4.RELEASE</org.springframework-version>
  <org.aspectj-version>1.6.10</org.aspectj-version>
  <org.slf4j-version>1.6.6</org.slf4j-version>

 </properties>
 <dependencies>
  <!-- Spring -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>${org.springframework-version}</version>
   <exclusions>
    <!-- Exclude Commons Logging in favor of SLF4j -->
    <exclusion>
     <groupId>commons-logging</groupId>
     <artifactId>commons-logging</artifactId>
     </exclusion>
   </exclusions>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${org.springframework-version}</version>
  </dependency>
    
  <!-- AspectJ -->
  <dependency>
   <groupId>org.aspectj</groupId>
   <artifactId>aspectjrt</artifactId>
   <version>${org.aspectj-version}</version>
  </dependency> 
  
  <!-- Logging -->
  <dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-api</artifactId>
   <version>${org.slf4j-version}</version>
  </dependency>
  <dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>jcl-over-slf4j</artifactId>
   <version>${org.slf4j-version}</version>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-log4j12</artifactId>
   <version>${org.slf4j-version}</version>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>log4j</groupId>
   <artifactId>log4j</artifactId>
   <version>1.2.15</version>
   <exclusions>
    <exclusion>
     <groupId>javax.mail</groupId>
     <artifactId>mail</artifactId>
    </exclusion>
    <exclusion>
     <groupId>javax.jms</groupId>
     <artifactId>jms</artifactId>
    </exclusion>
    <exclusion>
     <groupId>com.sun.jdmk</groupId>
     <artifactId>jmxtools</artifactId>
    </exclusion>
    <exclusion>
     <groupId>com.sun.jmx</groupId>
     <artifactId>jmxri</artifactId>
    </exclusion>
   </exclusions>
   <scope>runtime</scope>
  </dependency>

  <!-- @Inject -->
  <dependency>
   <groupId>javax.inject</groupId>
   <artifactId>javax.inject</artifactId>
   <version>1</version>
  </dependency>
    
  <!-- Servlet -->
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>servlet-api</artifactId>
   <version>2.5</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>javax.servlet.jsp</groupId>
   <artifactId>jsp-api</artifactId>
   <version>2.1</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>jstl</artifactId>
   <version>1.2</version>
  </dependency>
 
  <!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->
  <dependency>
      <groupId>javax.xml.bind</groupId>
      <artifactId>jaxb-api</artifactId>
      <version>2.3.0-b170201.1204</version>
  </dependency>
  
  <!-- https://mvnrepository.com/artifact/javax.activation/activation -->
  <dependency>
      <groupId>javax.activation</groupId>
      <artifactId>activation</artifactId>
      <version>1.1</version>
  </dependency>
  
  <!-- https://mvnrepository.com/artifact/org.glassfish.jaxb/jaxb-runtime -->
  <dependency>
      <groupId>org.glassfish.jaxb</groupId>
      <artifactId>jaxb-runtime</artifactId>
      <version>2.3.0-b170127.1453</version>
  </dependency>
 

  <!-- Test -->
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.7</version>
   <scope>test</scope>
  </dependency>       
 </dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


파일명: pom.xml


[첨부(Attachments)]

pom.zip




4. HomeController.java (com.website.example)


package com.website.example;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.website.example.vo.BoardListVO;
import com.website.example.vo.BoardVO;

/**
 * Handles requests for the application home page.
 */

@Controller
public class HomeController {
 
 private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
 
 /**
  * Simply selects the home view to render by returning its name.
  */
 @RequestMapping(value = "/", method = RequestMethod.GET)
 public String home(Locale locale, Model model) {
  logger.info("Welcome home! The client locale is {}.", locale);
  
  Date date = new Date();
  DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
  
  String formattedDate = dateFormat.format(date);
  
  model.addAttribute("serverTime", formattedDate );
  
  return "home";
 }
 
         @RequestMapping(value = "/dataTransform", produces="application/xml")
         @ResponseBody
         public BoardListVO dataTransform(Locale locale, Model model) {

  
              List<BoardVO> boardList = new ArrayList<BoardVO>();
              BoardVO vo = new BoardVO();
             vo.setId(1);
             vo.setTitle("야야야1");
             vo.setSearchCondition("하후");
             vo.setWriter("홍길동");
             vo.setRegDate(java.sql.Date.valueOf("2010-02-01"));
  
             boardList.add(vo);
  
            vo = new BoardVO();
            vo.setId(2);
            vo.setTitle("야야야2");
            vo.setSearchCondition("하후");
            vo.setWriter("홍길동");
            vo.setRegDate(java.sql.Date.valueOf("2010-03-01"));
            boardList.add(vo);
  
            BoardListVO boardListVO = new BoardListVO();
            boardListVO.setBoardList(boardList);
  
            System.out.println("가동중");
  
             return boardListVO;
        }
  
}


파일명: HomeController.java


[첨부(Attachments)]

HomeController.zip



5. BoardVO.java (com.website.example.vo)


package com.website.example.vo;

import java.sql.Date;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlTransient;


@XmlAccessorType(XmlAccessType.FIELD)
public class BoardVO {


         @XmlAttribute        // 사용 할 속성
         private int id;
         private String title;
         private String writer;
         private String content;
         private Date regDate;
 
        @XmlTransient        // 사용 안함
         private String searchCondition;
 
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getTitle() {
  return title;
 }
 public void setTitle(String title) {
  this.title = title;
 }
 public String getWriter() {
  return writer;
 }
 public void setWriter(String writer) {
  this.writer = writer;
 }
 public String getContent() {
  return content;
 }
 public void setContent(String content) {
  this.content = content;
 }
 public Date getRegDate() {
  return regDate;
 }
 public void setRegDate(Date regDate) {
  this.regDate = regDate;
 }
 public String getSearchCondition() {
  return searchCondition;
 }
 public void setSearchCondition(String searchCondition) {
  this.searchCondition = searchCondition;
 }
 
 
 
}


파일명: BoardVO.java


[첨부(Attachments)]

BoardVO.zip

HomeController.zip



6. BoardListVO.java (com.website.example.vo)


package com.website.example.vo;

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "boardList")
@XmlAccessorType(XmlAccessType.FIELD)
public class BoardListVO {


       @XmlElement(name = "board")
        private List<BoardVO> boardList;
 
        public List<BoardVO> getBoardList(){
                 return this.boardList;
        }
 
        public void setBoardList(List<BoardVO> boardList) {
                 this.boardList = boardList;
        }
 
}


파일명: BoardListVO.java


[첨부(Attachments)]

BoardListVO.zip



7. 출력 결과


스프링에서 출력한 XML이다.



그림 2. 출력 결과


BoardVO.zip

HomeController.zip



*음글(Conclsuion)


스프링 프레임워크로 Jaxb2 외 다수 라이브러리를 활용하여 XML을 생성하였다.



* 참고자료(References)


1. A Guide to JAXB Annotations - HowToDoInJava, https://howtodoinjava.com/jaxb/jaxb-annotations/, Accessed by 2020-10-11, Last Modified 2019-02.


2. [Java] JAXB 활용한 Java 객체의 XML 변환 방법, https://haenny.tistory.com/8, Accessed by 2020-10-11, Last Modified 2019-07-09.


반응형
728x90
300x250

[JSP] 28. Maven (Jaxb-runtime, activation, Jaxb Api, JSTL)을 활용한 XML 생성하기


JSP/Servlet으로도 Jaxb2와 각종 Library를 활용하여 XML을 생성할 수 있다.

일반 프로그래밍은 많이 접하였으나, XML은 잘 접해보지 않을 수도 있다.






1. XML을 JSP 파일에 수작업으로 입력하기


XML을 만드는 방법에는 수작업으로 하는 방법이 있겠다.


<xml>

<hama>

     <board>

     </board>

     <board>

     </board>

     <board>

     </board>

</hama>


예를 들면 이런 형태를 JSP에서 for문 등으로 VO를 읽어와서 뿌려주는 방법이 있겠다.

원시적인 방법이고, 자료가 3중, 4중으로 된 것을 처리하고자 했을 때는 수행빈도가 높아지는 단점이 있다.

코드도 복잡해진다.


물론 DB형태에 보관된 자료로 뿌릴 수도 있다.



<%@ page language="java" contentType="text/xml"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!-- 수작업으로 XML 규격을 만들어야 함. -->
<boardList>
 <board>
  <hello>asdf</hello>
 </board>
</boardList>


파일명: xml.jsp


[첨부(Attachments)]

xml.zip




2. JSP/Servlet - Maven Project


org.apache.maven.archetypes    |  maven-archetype-webapp    | 1.4(1.0)를 선택한다.


그림 1. JSP/XML 프로젝트 구성도




3. Java Compiler, Build Path, Project Factes


* Java Compiler - compiler compliance level 1.8
* Build Path -> JRE System Library 1.8
* Project Factes - Java : 1.8



4. Pom.xml 설정


Spring Framework에서도 <dependency>부분은 그대로 사용이 가능하다. (태스트 완료함)

pom.xml에 정의했던 라이브러리를 그대로 사용하는 것이다.

단, 출력하려고 했을 때, Jaxb에 대한 직접 출력을 정의하냐 안 하느냐 이런 차이가 있다.


 <!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
 <dependency>
     <groupId>javax.servlet</groupId>
     <artifactId>servlet-api</artifactId>
     <version>2.5</version>
     <scope>provided</scope>
 </dependency>
 
 <!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->
 <dependency>
     <groupId>javax.xml.bind</groupId>
     <artifactId>jaxb-api</artifactId>
     <version>2.3.0-b170201.1204</version>
 </dependency>
 
 <!-- https://mvnrepository.com/artifact/javax.activation/activation -->
 <dependency>
     <groupId>javax.activation</groupId>
     <artifactId>activation</artifactId>
     <version>1.1</version>
 </dependency>
 
 <!-- https://mvnrepository.com/artifact/org.glassfish.jaxb/jaxb-runtime -->
 <dependency>
     <groupId>org.glassfish.jaxb</groupId>
     <artifactId>jaxb-runtime</artifactId>
     <version>2.3.0-b170127.1453</version>
 </dependency>

 
 <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
 <dependency>
     <groupId>javax.servlet</groupId>
     <artifactId>jstl</artifactId>
     <version>1.2</version>
 </dependency>


파일명: pom.xml


[첨부(Attachments)]

pom.zip



5. BoardVO.java (com.website.example.vo)


package com.website.example.vo;

import java.sql.Date;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlTransient;


@XmlAccessorType(XmlAccessType.FIELD)
public class BoardVO {


        @XmlAttribute   // 보여줄 항목이다. 이런 뜻
         private int id;
         private String title;
         private String writer;
         private String content;
         private Date regDate;
 
        @XmlTransient    // 출력하지 않겠다.
         private String searchCondition;
 
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getTitle() {
  return title;
 }
 public void setTitle(String title) {
  this.title = title;
 }
 public String getWriter() {
  return writer;
 }
 public void setWriter(String writer) {
  this.writer = writer;
 }
 public String getContent() {
  return content;
 }
 public void setContent(String content) {
  this.content = content;
 }
 public Date getRegDate() {
  return regDate;
 }
 public void setRegDate(Date regDate) {
  this.regDate = regDate;
 }
 public String getSearchCondition() {
  return searchCondition;
 }
 public void setSearchCondition(String searchCondition) {
  this.searchCondition = searchCondition;
 }
 
 
 
}


파일명: BoardVO.java


[첨부(Attachments)]

BoardVO.zip


- 게시판 DB에서도 사용한다고 가정하자.



6. BoardListVO.java (com.website.example.vo)


package com.website.example.vo;

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "boardList")
@XmlAccessorType(XmlAccessType.FIELD)
public class BoardListVO {


         @XmlElement(name = "board")
         private List<BoardVO> boardList;
 
         public List<BoardVO> getBoardList(){
               return this.boardList;
         }
 
         public void setBoardList(List<BoardVO> boardList) {
               this.boardList = boardList;
         }
 
}


파일명: BoardListVO.java


[첨부(Attachments)]

BoardListVO.zip


루트 RootElement를 정의해줘야 XML 출력을 할 수 있는데, 출력을 그냥하는 건 아니고, List 형태로 구성된 VO(Value Object)를 출력하는 것이다.




7. HomeController.java (com.website.example.controller)


밑줄 친 부분들이 중요한 부분이다.


package com.website.example.controller;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import com.website.example.vo.BoardListVO;
import com.website.example.vo.BoardVO;


public class FrontController extends HttpServlet {
 private static final long serialVersionUID = 1L;
      
 
 protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  
            res.setContentType("text/xml;charset=utf-8");
    
            String result = setXmlData();
            PrintWriter out = res.getWriter();
  
            out.println(result);
  
            out.flush();
            out.close();

 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  
 }
 
        public String setXmlData(){
  
                 JAXBContext jc = null;
                 Marshaller marshaller = null;
   
                 List<BoardVO> boardList = new ArrayList<BoardVO>();
                 BoardListVO boardListVO = new BoardListVO();
  
                 OutputStream os = new ByteArrayOutputStream();

                 BoardVO vo = new BoardVO();
  
                 try {
                      jc = JAXBContext.newInstance(BoardListVO.class);
    
                 } catch (JAXBException e) {
                      e.printStackTrace();
                 }

                 vo.setId(1);
                 vo.setTitle("야야야1");
                 vo.setSearchCondition("하후");
                 vo.setWriter("홍길동");
                 vo.setRegDate(java.sql.Date.valueOf("2010-02-01"));
  
  boardList.add(vo);
  
  vo = new BoardVO();
  vo.setId(2);
  vo.setTitle("야야야2");
  vo.setSearchCondition("하후");
  vo.setWriter("홍길동");
  vo.setRegDate(java.sql.Date.valueOf("2010-03-01"));

               boardList.add(vo);

               boardListVO.setBoardList(boardList);
  
                try {
                       marshaller = jc.createMarshaller();
                       marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
                       marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
   
                       // marshaller.marshal(boardListVO, System.out);
                       marshaller.marshal(boardListVO, os);
   
                } catch (JAXBException e) {
                       e.printStackTrace();
    
                }

  
                // System.out.println("XML출력:" + os.toString());
   
                return os.toString();

  
        }

}


파일명: FrontController.java


[첨부(Attachments)]

FrontController.zip




8. web.xml (/src/main/webapp/WEB-INF/web.xml)


<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
   <servlet-name>FrontController</servlet-name>
   <display-name>FrontController</display-name>
   <description></description>
   <servlet-class>com.website.example.controller.FrontController</servlet-class>
  </servlet>
  <servlet-mapping>
           <servlet-name>FrontController</servlet-name>
           <url-pattern>/dataTransform.do</url-pattern>
  </servlet-mapping>
</web-app>


파일명: web.java


[첨부(Attachments)]

web.zip



9. 출력 결과


완성된 결과물이다.



그림 2. XML.jsp 파일 (수작업 방법)



그림 3. Jaxb2 외 다수 라이브러리로 적



* 맺음글(Conclusion)


JSP/Servlet 기반에서 XML 출력하는 방법에 대해서 살펴보았다.

반응형

+ Recent posts