ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Spring] 01-11. ModelAttribute Annotation을 이용한 모델 데이터 처리
    프로그래밍/Spring 2015. 9. 15. 12:32
    반응형

    @ModelAttribute Annotation을 이용하면 다음의 두 가지 작업을 수행할 수 있다.

    - @ModelAttribute Annotation이 적용되지 않은 별도 메서드로 모델에 추가될 객체를 생성

    - 커맨드 객체의 초기화 작업을 수행


    * 참조 데이터 생성


    - WEB Application을 구현하다 보면 동일한 모델 데이터를 두 개 이상의 요청 처리 결과 화면에서 보여주어야 할 때가 있다.

    예를 들어, 검색 메인 화면과 검색 결과 화면에서 검색 타입과 인기 검색어를 보여줄 수 있을 것이다. 이 경우 이들 공통 모델 데이터를 설정해 주는 메서드를 구현한 뒤 요청 처리 메서드에서 호출하도록 구현할 수 있을 것이다.


    @ModelAttribute Annotation을 사용하면 이런 단점 없이 두 개 이상의 요청 처리 메서드에서 공통으로 사용되는 모델을 설정할 수가 있다. @ModelAttribute Annotation을 메서드에 적용하면 해당 메서드가 생성한 객체가 뷰에 전달된다. 따라서, @ModelAttribute Annotation을 사용하면 두 개 이상의 요청 처리 메서드에서 공통으로 사용되는 모델 객체를 생성할 수 있다.




    [GameSearchController.java]

    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
    58
    59
    60
    package spring.chap06.controller;
     
    import java.util.ArrayList;
    import java.util.List;
     
    import spring.chap06.service.SearchCommand;
    import spring.chap06.service.SearchResult;
    import spring.chap06.service.SearchService;
    import spring.chap06.service.SearchType;
     
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.servlet.ModelAndView;
     
    @Controller
    public class GameSearchController {
        @Autowired
        private SearchService searchService;
     
        @ModelAttribute("searchTypeList")
        public List<SearchType> referenceSearchTypeList() {
            List<SearchType> options = new ArrayList<SearchType>();
            options.add(new SearchType(1"전체"));
            options.add(new SearchType(2"아이템"));
            options.add(new SearchType(3"캐릭터"));
            return options;
        }
     
        @ModelAttribute("popularQueryList")
        public String[] getPopularQueryList() {
            return new String[] { "게임""창천2""위메이드" };
        }
     
        @RequestMapping("/search/main.do")
        public String main() {
            return "search/main";
        }
     
        @RequestMapping("/search/game.do")
        public ModelAndView search(@ModelAttribute("command") SearchCommand command) {
            ModelAndView mav = new ModelAndView("search/game");
            System.out.println("검색어 = " + command.getQuery().toUpperCase());
            SearchResult result = searchService.search(command);
            mav.addObject("searchResult", result);
            return mav;
        }
     
        @ExceptionHandler(NullPointerException.class)
        public String handleNullPointerException(NullPointerException ex) {
            return "error/nullException";
        }
     
        public void setSearchService(SearchService searchService) {
            this.searchService = searchService;
        }
     
    }
    cs


    [SearchCommand.java]

    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
    package spring.chap06.service;
     
    public class SearchCommand {
     
        private String type;
        private String query;
        private int page;
     
        public String getType() {
            return type;
        }
     
        public void setType(String type) {
            this.type = type;
        }
     
        public String getQuery() {
            return query;
        }
     
        public void setQuery(String query) {
            this.query = query;
        }
     
        public int getPage() {
            return page;
        }
     
        public void setPage(int page) {
            this.page = page;
        }
     
    }
    cs


    [SearchType.java]

    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
    package spring.chap06.service;
     
    public class SearchType {
     
        private int code;
        private String text;
     
        public SearchType(int code, String text) {
            this.code = code;
            this.text = text;
        }
     
        public int getCode() {
            return code;
        }
     
        public void setCode(int code) {
            this.code = code;
        }
     
        public String getText() {
            return text;
        }
     
        public void setText(String text) {
            this.text = text;
        }
     
    }
    cs


    [SearchService.java]

    1
    2
    3
    4
    5
    6
    7
    8
    9
    package spring.chap06.service;
     
    public class SearchService {
     
        public SearchResult search(SearchCommand command) {
            return new SearchResult();
        }
     
    }
    cs


    [SearchResult.java]

    1
    2
    3
    4
    5
    package spring.chap06.service;
     
    public class SearchResult {
     
    }
    cs

    [dispatcher-servlet.xml]

    1
    2
    3
    4
    <bean class="spring.chap06.controller.GameSearchController"
            p:searchService-ref="searchService" />
     
        <bean id="searchService" class="spring.chap06.service.SearchService" />
    cs




    [/WEB-INF/view/search/main.jsp]

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    <%@ page language="java" contentType="text/html; charset=EUC-KR"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
    <title>게임 검색 메인</title>
    </head>
    <body>
        인기 키워드:
        <c:forEach var="popularQuery" items="${popularQueryList}">${popularQuery} </c:forEach>
        <form action="game.do">
            <select name="type">
                <c:forEach var="searchType" items="${searchTypeList}">
                    <option value="${searchType.code}">${searchType.text}</option>
                </c:forEach>
            </select> <input type="text" name="query" value="" /> <input type="submit"
                value="검색" />
        </form>
    </body>
    </html>
    cs


    [/WEB-INF/view/search/game.jsp]

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    <%@ page language="java" contentType="text/html; charset=EUC-KR"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
    <title>게임 검색 결과</title>
    </head>
    <body>
        인기 키워드:
        <c:forEach var="popularQuery" items="${popularQueryList}">${popularQuery} </c:forEach>
        <form action="game.do">
            <select name="type">
                <c:forEach var="searchType" items="${searchTypeList}">
                    <option value="${searchType.code}"
                        <c:if test="${command.type == searchType.code}">selected</c:if>>
                        ${searchType.text}</option>
                </c:forEach>
            </select> <input type="text" name="query" value="${command.query}" /<input
                type="submit" value="검색" />
        </form>
        검색 결과: ${searchResult}
    </body>
    </html>
     
    cs


    서버 구동후 http://localhost:8080/Spring06/search/main.do 으로 구동

    반응형

    댓글

Designed by Tistory.