ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Spring] JAVA 객체를 XML로 페이지에 출력해보기
    Programming/Spring 2015. 10. 25. 22:17

     ( 저 혼자 정리차원에서 만든 것이라 부족한게 보일 수도 있습니다. 틀린 것이 있거나 의견있으시면 피드백 부탁드립니다! )


    XML을 웹에 출력할 때는 비교적 쉽게 출력할 수 있었다. 


    물론 찾아보고 이런 노가다를 통해 4~5시간 정도 걸린 것 같음.


    일단 XML파일로 만들 객체를 만들어보자


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    package org.galket.persistance;
     
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlRootElement;
     
     
    @XmlRootElement(name = "root")
    public class Root {
     
        private String result;
        
        public Root(){
            
        }
        
     
        public Root(String result) {
            super();
            this.result = result;
        }
     
     
        @XmlElement
        public String getResult() {
            return result;
        }
     
        public void setResult(String result) {
            this.result = result;
        }
     
        @Override
        public String toString() {
            return "Root [result=" + result + "]";
        }
     
        
        
    }
     
     
     
    cs


    코드를 분석해보면, 빈 생성자를 하나 만들고, 그 생성자를 상속받는 생성자를 하나 더 만든다.


    그후 getter/setter를 설정 해준 모습이다. 


    여기서 중요한 것은 바로 @XmlRootElement와 @XmlElement다.

    @XmlRootElement는 XML의 모든 요소를 포함하고 있는 상위태그다.

    어노테이션 옆에 name값을 설정해 준 것이 보일텐데, 이건 상위태그의 이름을 설정해주는것이라고 할 수 있다.

    아마 결과를 보면 바로 이해가 갈 것이다.

    @XmlElement는 @XmlRootElement의 요소다.

    Element로 넣고싶은 메소드에 이 어노테이션을 붙여주면 된다.

    그다음 웹에 출력해보자.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    package org.galket.app;
     
    import java.text.DateFormat;
    import java.util.Date;
    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;
     
    /**
     * Handles requests for the application home page.
     */
    @Controller
    @RequestMapping(value = "/")
    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";
        }
     
        Root root;
     
        @RequestMapping(value = "/service")
        @ResponseBody
        public Root test1(){
            
            root = new Root("success!!")
     
            return root;
     
        }
        
    }
    cs

    다음과 같이 HomeController에 RequestMapping을 '/service'로 해주었기 때문에 이 주소로 들어가면 XML이 출력이 된다.

    (참고로 위에 메인페이지는 클라이언트가 /test로 접근할 때 갈 수 있도록 경로를 변경하였다.) 

    또한 별도의 jsp파일 없이 바로 출력될 수 있도록 @ResponseBody태그도 붙여주었다.

    그럼 바로 접근해보면

    /test/service로 들어갔을때 다음과 같이 <root>태그안에 <result>태그가 보이고 그 안의 값이 success!!로 설정된 것을 볼 수 있다.



Designed by Tistory.