Notice
Recent Posts
Recent Comments
Link
«   2025/01   »
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
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

Field값 검증 본문

Project/대중교통 길찾기

Field값 검증

Seung__ 2022. 2. 7. 21:27

 

현재 출발지 or 목적지를 입력을 하지 않으면 IllegalArgumentException이 발생한다.

 

Controller에서 받은 값에 문제가 있을 경우 view에 에러 메세지를 전달하도록 수정해 보자.

 

View에서는 전달받은 에러 메시지를 출력할 것이다.

 

 

1. Controller


@Slf4j
@Controller
@RequiredArgsConstructor
public class ApiController {

    private final OdSayClient odSayClient;
    private final GoogleClient googleClient;
    Map<String, String> errors = new LinkedHashMap<>();

    @GetMapping("/")
    public String home4(Model model){
        model.addAttribute("searchLocationReq", new SearchLocationReq());
        return "searchRouteWithRealTimeInfo";
    }


    @PostMapping("/With-realTimeInfo")
    public String searchRoute3(@ModelAttribute SearchLocationReq searchLocationReq, Model model){
        errors.clear();
        errors = fieldValidation(searchLocationReq);

        if(!errors.isEmpty()){
            model.addAttribute("errors", errors);
            return "searchRouteWithRealTimeInfo";
        }

        ResFactory factory = new ResFactory(searchLocationReq, model, googleClient, odSayClient);
        model = factory.getResult();
        return searchLocationReq.getMiddle().isEmpty()? "resultPage3-1":"resultPage3";
    }

    public Map<String, String> fieldValidation(SearchLocationReq searchLocationReq){
        if (searchLocationReq.getStart().isEmpty()){
            log.info("[ApiController] form 입력값 오류 발생");
            log.info("[ApiController] 'searchLocationReq'is empty" );
            errors.put("start", "'출발지'는 필수 값 입니다.");
        }

        if (searchLocationReq.getEnd().isEmpty()){
            log.info("[ApiController] form 입력값 오류 발생");
            log.info("[ApiController] 'End'is empty");
            errors.put("end", "'목적지'는 필수 값 입니다.");
        }
        return errors;
    }

}

 

간단하게 출발지, 도착지를 입력을 하지 않았으면 이에 해당하는 에러메세지를 model에 담아서 view에 넘긴다.

 

 

2. View


각 필드에 해당하는 에러 메시지가 있는 경우 메시지를 출력한다.

<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Find Route</title>
</head>
<style>
    .fieldError {
        border-color: #dc3545;
        color: #dc3545;
    }
</style>
<body>
<H1 align="center"><b>대중교통 길찾기</b></H1>

<div class="search box">
    <div class="container" style="max-width: 600px">
        <form action="/With-realTimeInfo" th:action="@{/With-realTimeInfo}" th:object="${searchLocationReq}" method="post">
            <div style="margin-bottom: 5px">
                <div class="input-group">
                    <span class="input-group-text" id="basic-addon1">출발지</span>
                    <input type="text" id="start" th:field="*{start}" class="form-control" placeholder="출발지" aria-label="start" aria-describedby="basic-addon1">
                </div>
                <div th:if="${errors?.containsKey('start')}" th:text="${errors['start']}"
                     th:class="${errors?.containsKey('start')} ? 'fieldError' : 'form-control'"
                     style="display:inline-flex">
                    출발지 입력 오류
                </div>
            </div>
            <div class="input-group" style="margin-bottom: 5px">
                <span class="input-group-text" id="basic-addon2">경유지</span>
                <input type="text" id="wayPoint" th:field="*{middle}" class="form-control" placeholder="경유지" aria-label="start" aria-describedby="basic-addon1">
            </div>
            <div style="margin-bottom: 5px">
                <div class="input-group">
                    <span class="input-group-text" id="basic-addon3">목적지</span>
                    <input type="text" id="end" th:field="*{end}" class="form-control" placeholder="목적지" aria-label="end" aria-describedby="basic-addon1">
                </div>
                <div th:if="${errors?.containsKey('end')}" th:text="${errors['end']}"
                     th:class="${errors?.containsKey('end')} ? 'fieldError' : 'form-control'">
                    목적지 입력 오류
                </div>
            </div>
            <button type="submit" class="btn btn-primary" th:onclick="">검색</button>
        </form>
    </div>
</div>

</body>
</html>

 

3. 결과


log도 잘 남는것을 확인할 수 있다.

[ApiController] form 입력값 오류 발생
[ApiController] 'start'is empty
[ApiController] form 입력값 오류 발생
[ApiController] 'End'is empty
[ApiController] form 입력값 오류 발생
[ApiController] 'start'is empty
[ApiController] form 입력값 오류 발생
[ApiController] 'End'is empty

 

 

4. GitHub: 220207 Field Validation


 

GitHub - bsh6463/commuteMap

Contribute to bsh6463/commuteMap development by creating an account on GitHub.

github.com

 

Comments