ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 핸들러 메소드 7부: 폼 서브밋 (에러 처리)
    SPRING/스프링 MVC 2021. 7. 4. 10:19

    바인딩 에러 발생 시 Model에 담기는 정보 

    - Event 

    - BindingResult.event 

     

    Post / Redirect / Get 패턴 

    - https://en.wikipedia.org/wiki/Post/Redirect/Get 

    - Post 이후에 브라우저를 리프래시 하더라도 폼 서브밋이 발생하지 않도록 하는 패턴

     

    @Controller
    public class SampleController2 {
    
        // Form 화면
        @GetMapping("/events/form")
        public String eventsForm(Model model) {
            Event newEvent = new Event();
            newEvent.setLimit(50);
            model.addAttribute("event",newEvent);
            return "/events/form";
        }
    
        // form 전송
        @PostMapping("/events")
        public String createEvent(@ModelAttribute @Validated Event event,
                              BindingResult bindingResult, Model model) {
    
            // @Validated 어노테이션을 통하여 Validation 체크에 맞지 않으면 다시 form으로 리턴
            if(bindingResult.hasErrors()) {
                return "/events/form";
            }
    
            List<Event> eventList = new ArrayList<>();
            eventList.add(event);
            model.addAttribute("eventList",eventList);
            // save 생략
    
            // POST-REDIRECT-GET 패턴
            // ( Post 이후에 브라우저를 리프래시 하더라도 폼 서브밋이 발생하지 않도록 하는 패턴)
            return "redirect:/events/list";
        }
    
        @GetMapping("/events/list")
        public String getEvents(Model model) {
    
            // 리스트를 불러오는 부분
            Event event = new Event();
            event.setName("spring");
            event.setLimit(10);
    
            List<Event> eventList = new ArrayList<>();
            eventList.add(event);
    
            model.addAttribute(eventList);
            return "/events/list";
        }
        
    }
    

     

    - form.html  소스

    <!doctype html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Create New Event</title>
    </head>
    <body>
    <form action="#" th:action="@{/events}"  method="post" th:object="${event}">
        <p th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Incorrect name</p>
        <p th:if="${#fields.hasErrors('limit')}" th:errors="*{limit}">Incorrect limit</p>
        <input type="text" title="name" th:field="*{name}">
        <input type="text" title="limit" th:field="*{limit}">
        <input type="submit" value="Create"/>
    </form>
    </body>
    </html>

    list.html 소스

    <!doctype html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Create New Event</title>
    </head>
    <body>
    <a th:href="@{/events/form}">Create New Event</a>
    <div th:unless="${#lists.isEmpty(eventList)}">
        <ul th:each="event: ${eventList}">
            <p th:text="${event.Name}">Event Name</p>
        </ul>
    </div>
    </body>
    </html>

     

    Validation에 어긋나는 데이터를 입력하고 submit을 아래와 같이 Validation Error 내용은 출력

    정상적인 내용을 Submit하면 아래와 같은 화면 출력

     

     

     

Designed by Tistory.