Spring Boot Starter Validation을 이용하여 검증 추가하기

Soo·2024년 3월 12일

이번 포스팅에서는 Spring Boot Validation을 정리하겠습니다.

간단하게 프론트에서 검증을 할 수 있는 법이 있습니다.

todo.jps

  • required=”required”를 사용하면 입력 없이 요청을 하려는 경우 입력창이 비어있으면 안된다는 경고창을 띄워줍니다.
  • 하지만 이 방법은 쉽게 해결될 수 있는 검증이기 때문에 결국에는 서버에서 최종 검증을 해주어야 합니다.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <link href="webjars\bootstrap\5.1.3\css\bootstrap.min.css" rel="stylesheet">
    <title>Add Todos Page</title>
</head>
<body>
<div class="container">
    <h1>Enter Todo Details</h1>
    <form method="post">
        Description: <input type="text" name="description" required="required"/>
        <input type="submit" class="btn btn-success"/>
    </form>
</div>
<script src="webjars\bootstrap\5.1.3\js\bootstrap.bundle.min.js"></script>
<script src="webjars\jquery\3.6.0\jquery.min.js"></script>
</body>
</html>

Spring Boot MVC 검증을 추가하는 방법 네 단계

  1. xml을 사용해서 spring-boot-starter-validation 추가
  2. 커멘드 빈 또는 양식 보조 객체
  3. Bean에 검증을 추가하는 단계
  4. 검증 오류를 뷰에 표시하는 단계

첫 번째, xml을 사용해서 spring-boot-starter-validation 추가

pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

두 번째, 커맨드 빈 또는 양식 보조 객체 구현

TodoController.class

addNewTodo()에서 @RequestParam으로 description을 받지 않고 Todo 객체를 통해서 직접 객체를 바인딩 받는다.

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import java.time.LocalDate;
import java.util.List;

@Controller
@SessionAttributes("name")
public class TodoController {

    private TodoService todoService;

    public TodoController(TodoService todoService) {
        this.todoService = todoService;
    }

    //list-todos
    @RequestMapping("/list-todos")
    public String listAllTodos(ModelMap model) {
        List<Todo> todos = todoService.findByUsername("test1");
        model.addAttribute("todos", todos);

        return "listTodos";
    }

    @RequestMapping(value = "/add-todo", method = RequestMethod.GET)
    public String showNewTodoPage(ModelMap model) {
        String username = (String) model.get("name");
        Todo todo = new Todo(0, username, "", LocalDate.now().plusYears(1), false);
        model.put("todo", todo);
        return "todo";
    }

    @RequestMapping(value = "/add-todo", method = RequestMethod.POST)
    public String addNewTodo(ModelMap model, Todo todo) {
        String username = (String) model.get("name");
        todoService.addTodo(username, todo.getDescription(), LocalDate.now().plusYears(1), false);
        return "redirect:list-todos";
    }
}

Todo 객체를 jps에서 사용하기 위해서는 Spring 양식 태그 라이브러리를 사용해야 합니다.

todo.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>를 추가합니다.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<html>
<head>
    <link href="webjars\bootstrap\5.1.3\css\bootstrap.min.css" rel="stylesheet">
    <title>Add Todos Page</title>
</head>
<body>
<div class="container">
    <h1>Enter Todo Details</h1>
    <form:form method="post" modelAttribute="todo">
        Description: <form:input type="text" name="description" path="description"
                                 required="required"/>
        <form:input type="hidden" path="id"/>
        <form:input type="hidden" path="done"/>
        <input type="submit" class="btn btn-success"/>
    </form:form>
</div>
<script src="webjars\bootstrap\5.1.3\js\bootstrap.bundle.min.js"></script>
<script src="webjars\jquery\3.6.0\jquery.min.js"></script>
</body>
</html>

path 속성은 폼 요소와 폼 데이터 객체의 속성을 연결하여 데이터의 흐름을 제어합니다.

예를 들어, path="description"를 사용하면 폼 요소의 값을 description 속성에 바인딩합니다. 폼 요소의 값이 변경되면 자동으로 해당 속성의 값도 변경됩니다.

0개의 댓글