고민보다Go

(Thymeleaf 기본 문법) form태그에서 사용하는 타임리프 속성 본문

타임리프

(Thymeleaf 기본 문법) form태그에서 사용하는 타임리프 속성

나를 조각해나가자 2024. 4. 5. 09:38

form태그의 경우 method="post"로 하면 controller에서는 @PostMapping으로 한다!

@GetMapping에서 오는 data와 @PostMapping에서 오는 data를 구분할 수 있다는 것이다

 

- 다음과 같이 컨트롤러를 작성

@GetMapping("/formtest")
public String formtest(Model model){
	model.addAttribute("data","thymeleaf");
    return "basic/form_test";
}

@PostMapping("/formtest")
public String runformtest(Model model, String test1, String thymeleaf){ 
	System.out.printLn("test1=>"+test1);
    System.out.printLn("thymeleaf=>"+thymeleaf);
    return "basic/form_test";
}

 

-html은 다음과 같이 작성

<form action="/th/formtest" method="post">
 	<!--최초로 보여질때는 GetMapping이니까 data는 "thymeleaf" 로 name, value모두 찍힌다.-->
	<input type="text" name="test1" value="basic" class="myinput" th:name="${data}" th:value="${data}"> 
    <!--attrappend: 명시한 요소 뒤에 추가, attrprepend: 명시한 요소 앞에 추가, classappend:클래스명 앞에 추가 -->
	<input type="text" name="test1" value="basic" class="myinput" th:attrappend="class='_a'">
	<input type="text" name="test2" value="basic" class="myinput" th:attrprepend="class='a_'">	
    <input type="text" name="test3" value="basic" class="myinput" th:classappend="a">
    <br/><br/>
    <input type="checkbox" name="subject" value="java" checked>java
    <input type="checkbox" name="subject" value="spring" th:checked="true">spring
    <input type="checkbox" name="subject" value="hadoop" th:checked="false">hadoop
    
    <input type="submit" value="서버로 전송하기" >
</form>

 

 

 

클래스명이 append한대로 반영된걸 볼수 있다. name="${data}"은 name="thymeleaf"가 되어 @PostMapping으로 넘어갈때 String thymeleaf로 파라미터 변수명을 적어준 것이다.

 

submit버튼 눌러서 @PostMapping으로 넘기면

다음과 같이 콘솔창에 찍히는 것을 볼 수 있다.