일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- joinfetch
- 프로젝트생성
- springflow
- 대량쿼리
- 페이징
- jQuery값전달
- JPQL
- namedQuery
- values()
- calendar
- javaservlet
- 자바서블릿
- Generic
- jscalendar
- 제너릭
- 제네릭
- Hibernate
- fullcalendar
- 페치조인
- javascriptcalendar
- jQuery값전송
- 벌크연산
- jQueryUI
- paging
- JQuery
- LIST
- fetchjoin
- JPA
- 엔티티직접사용
- 스프링데이터흐름
- Today
- Total
가자공부하러!
Spring Boot Example - Creating a Form 본문
Spring Boot Example - Creating a Form
원문 : https://www.thymeleaf.org/doc/tutorials
1. Handlig the command object
Command object is the name Spring MVC gives to form-backing beans, this is, to objects that model a form’s fields and provide getter and setter methods that will be used by the framework for establishing and obtaining the values input by the user at the browser side.
Thymeleaf requires you to specify the command object by using a th:object
attribute in your <form>
tag:
> Command object는 Spring MVC가 form-backing beans에 주는 이름인데, 폼의 필드를 모델링하고 브라우저 측에서 사용자가 입력 한 값을 설정하고 얻기 위해 프레임워크에서 사용할 getter, setter 메서드를 제공합니다.
Thymeleaf에서는 <form>태그 안에서 th:object 속성을 사용하여 command object를 지정해야 합니다.
1 2 3 | <form action="#" th:action="@{/seedstartermng}" th:object="${seedStarter}" method="post"> ... </form> | cs |
This is consistent with other uses of th:object,
but in fact this specific scenario adds some limitations in order to correctly integrate with Spring MVC’s infrastructure:
- Values for
th:object
attributes in form tags must be variable expressions (${...}
) specifying only the name of a model attribute, without property navigation. This means that an expression like${seedStarter}
is valid, but${seedStarter.data}
would not be. - Once inside the
<form>
tag, no otherth:object
attribute can be specified. This is consistent with the fact that HTML forms cannot be nested.
-
form 태그 안에 th:object 속성값은 속성탐색 없이 오직 모델 속성의 이름만 지정하는 $({...})표현식이여야만 합니다. 즉, ${seedStarter}는 유효하지만, ${seedStarter.data}는 유효하지 않아요.
-
한 번 <form>태그 안에 들어가면, 다른 th:object 속성은 지정할 수 없어요. 이는 HTML 양식을 중첩할 수 없다는 사실과 일치하죠.
2. Inputs
Let’s see now how to add an input to our form:
> 어떻게 우리 폼에 input을 추가하는지 봅시다:
1 | <input type="text" th:field="*{datePlanted}" /> | cs |
As you can see, we are introducing a new attribute here: th:field.
This is a very important feature for Spring MVC integration because it
does all the heavy work of binding your input with a property in the
form-backing bean. You can see it as an equivalent of the path attribute
in a tag from Spring MVC’s JSP tag library.
> 새로운 속성 th:field입니다. 이 속성은 Spring MVC 통합을 위해 매우 중요한 기능입니다. 왜냐하면 이것은 form-backing bean 내부의 속성과 너의 입력을 묶어주는 모든 무거운 작업을 수행하기 때문이죠. Spring MVC JSP 태그 라이브러리에서 태그의 path 속성과 동일한 것으로 볼 수있어요.
The th:field
attribute behaves differently depending on whether it is attached to an <input>
, <select>
or <textarea>
tag (and also depending on the specific type of <input>
tag). In this case (input[type=text]
), the above line of code is similar to:
> th:field 속성은 어디에 붙는지에 따라 다르게 동작합니다. <input>, <select>, <textarea>태그 등에 포함될 수 있어요. (<input>태그의 type에 따라서도 달라집니다). 아래 예시는 위에 적혀있던 코드와 유사합니다.
1 | <input type="text" id="datePlanted" name="datePlanted" th:value="*{datePlanted}" /> | cs |
…but in fact it is a little bit more than that, because th:field
will also apply the registered Spring Conversion Service, including the DateFormatter
we saw before (even if the field expression is not double-bracketed).
Thanks to this, the date will be shown correctly formatted.
> 하지만 실제로 첫 번째 코드보다는 더 길죠, th:field는 이전에 본 DataFormatter를 포함하여 미리 등록 된 Spring Conversion Service를 적용하기 때문이야. 그 덕분에 날짜를 올바르게 표시할 수 있어요.
Values for th:field
attributes must be selection expressions (*{...}
),
which makes sense given the fact that they will be evaluated on the
form-backing bean and not on the context variables (or model attributes
in Spring MVC jargon).
> th:field 속성의 값은 선택 표현식(*{...})이어야 하며, 컨텍스트 변수(또는 Spring MVC jargon의 모델 속성)가 아니라 form-backing bean에서 평가된다는 사실과 일맥상통합니다.
Contrary to the ones in th:object
, these expressions can include property navigation (in fact any expression allowed for the path attribute of a <form:input>
JSP tag will be allowed here).
> th:object와 달리, 이 표현식은 특정 네비게이션을 포함할 수 있습니다.(사실 <form:input> JSP태그의 경로 속성에 허용된 모든 표현식이 허용돼요.)
Note that th:field
also understands the new types of <input>
element introduced by HTML5 like <input type="datetime" ... />
, <input type="color" ... />
, etc., effectively adding complete HTML5 support to Spring MVC.
3. Check Box
th:field
also allows us to define checkbox inputs. Let’s see an example from our HTML page:
> th:field태그는 당연히 checkbox 태그에도 쓸 수 있지요. 봅시다.
1 2 3 4 | <div> <label th:for="${#ids.next('covered')}" th:text="#{seedstarter.covered}">Covered</label> <input type="checkbox" th:field="*{covered}" /> </div> | cs |
Note there’s some fine stuff here besides the checkbox itself, like an externalized label and also the use of the #ids.next('covered')
function for obtaining the value that will be applied to the id attribute of the checkbox input.
>
Why do we need this dynamic generation of an id attribute for this
field? Because checkboxes are potentially multi-valued, and thus their
id values will always be suffixed a sequence number (by internally using
the #ids.seq(...)
function) in order to ensure that each of the checkbox inputs for the same property has a different id value.
We can see this more easily if we look at such a multi-valued checkbox field:
<ul>
<li th:each="feat : ${allFeatures}">
<input type="checkbox" th:field="*{features}" th:value="${feat}" />
<label th:for="${#ids.prev('features')}"
th:text="#{${'seedstarter.feature.' + feat}}">Heating</label>
</li>
</ul>
Note that we’ve added a th:value
attribute this time, because the features field is not a boolean like covered was, but instead is an array of values.
Let’s see the HTML output generated by this code:
<ul>
<li>
<input id="features1" name="features" type="checkbox" value="SEEDSTARTER_SPECIFIC_SUBSTRATE" />
<input name="_features" type="hidden" value="on" />
<label for="features1">Seed starter-specific substrate</label>
</li>
<li>
<input id="features2" name="features" type="checkbox" value="FERTILIZER" />
<input name="_features" type="hidden" value="on" />
<label for="features2">Fertilizer used</label>
</li>
<li>
<input id="features3" name="features" type="checkbox" value="PH_CORRECTOR" />
<input name="_features" type="hidden" value="on" />
<label for="features3">PH Corrector used</label>
</li>
</ul>
We can see here how a sequence suffix is added to each input’s id attribute, and how the #ids.prev(...)
function allows us to retrieve the last sequence value generated for a specific input id.
Don’t worry about those hidden inputs with
name="_features"
: they are automatically added in order to avoid problems with browsers not sending unchecked checkbox values to the server upon form submission.
Also note that if our features property contained some selected values in our form-backing bean, th:field
would have taken care of that and would have added a checked="checked"
attribute to the corresponding input tags.
'공부 > 영어' 카테고리의 다른 글
Spring Boot Thymeleaf Asterisk-syntax (2) | 2019.07.20 |
---|---|
Java 8 Streams (tutorialspoint.com) (0) | 2019.05.18 |