복붙노트

[SPRING] 어떻게 thymeleaf th : 다른 변수에서 필드 값을 설정하는 방법

SPRING

어떻게 thymeleaf th : 다른 변수에서 필드 값을 설정하는 방법

하나의 개체에서 기본값을 설정하고 다른 개체의 최종 값을 저장해야하는 간단한 텍스트 입력 필드가 있습니다. 다음 코드는 작동하지 않습니다.

<div th:object="${form}">
    <input class="form-control"
           type="text"
           th:value="${client.name}"  //this line is ignored
           th:field="*{clientName}"/>
</div>

양식은 DTO 개체이고 클라이언트는 데이터베이스의 Entity 개체입니다.

이 상황을 해결하는 올바른 방법은 무엇입니까?

내 말은 작동하지 않음으로써 초기 값은 client.name = "Foo"이고 form.clientName = null이라고 말할 수 있습니다.  입력 필드 표시 값은 "Foo"이고 양식 제출 후 form.clientName 값은 "Foo"가되어야합니다. 그러나 입력 필드에는 아무것도 표시되지 않고 제출시 form.clientName 값은 여전히 ​​null입니다.

누구나 관심이있는 경우 다음 구조를 사용하여이 문제를 해결했습니다 (다른 질문에서 답을 찾았 음).

th:attr="value = ${client.name}"

해결법

  1. ==============================

    1.이 방법에 접근 할 수 있습니다.

    이 방법에 접근 할 수 있습니다.

    th : ​​field 대신에 html id & name을 사용하십시오. th : ​​값을 사용하여 값 설정

    <input class="form-control"
               type="text"
               th:value="${client.name}" id="clientName" name="clientName" />
    

    희망이 당신을 도울 것입니다.

  2. ==============================

    2.양식의 가치를 유지하면서 페이지를 다시 방문 할 필요가없는 경우 다음을 수행 할 수 있습니다.

    양식의 가치를 유지하면서 페이지를 다시 방문 할 필요가없는 경우 다음을 수행 할 수 있습니다.

    <form method="post" th:action="@{''}" th:object="${form}">
        <input class="form-control"
               type="text"
               th:field="${client.name}"/>
    

    그것은 어떤 종류의 마술입니다.

    사용자 입력 실수로 페이지에 다시 입력하는 것처럼 양식의 입력 값을 유지하는 것이 중요하면 다음을 수행해야합니다.

    <form method="post" th:action="@{''}" th:object="${form}">
        <input class="form-control"
               type="text"
               th:name="name"
               th:value="${form.name != null} ? ${form.name} : ${client.name}"/>
    

    그 의미는 :

    클라이언트 bean을 양식 bean에 맵핑하지 않아도됩니다. 그리고 일단 양식을 제출하면 값은 arn't null이지만 ""(비어 있음)

  3. ==============================

    3.올바른 접근법은 전처리를 사용하는 것입니다.

    올바른 접근법은 전처리를 사용하는 것입니다.

    예를 들어

    th : ​​field = "* {__ $ {myVar} __}"

  4. ==============================

    4.그것에는 2 가지 가능한 해결책이있다 :

    그것에는 2 가지 가능한 해결책이있다 :

    1) javascript로보기에서 가져올 수 있습니다 ... (권장하지 않음)

    <input class="form-control"
           type="text"
           id="tbFormControll"
           th:field="*{clientName}"/>
    
    <script type="text/javascript">
            document.getElementById("tbFormControll").value = "default";
    </script>
    

    2) 또는 더 나은 솔루션은 컨트롤러에서 GET 작업의 뷰에 첨부 할 모델의 값을 설정하는 것입니다. 컨트롤러의 값을 변경하거나 $ client.name에서 Java 객체를 만들고 setClientName을 호출 할 수도 있습니다.

    public class FormControllModel {
        ...
        private String clientName = "default";
        public String getClientName () {
            return clientName;
        }
        public void setClientName (String value) {
            clientName = value;
        }
        ...
    }
    

    도움이되기를 바랍니다.

  5. from https://stackoverflow.com/questions/25027801/how-to-set-thymeleaf-thfield-value-from-other-variable by cc-by-sa and MIT license