Thymeleaf는 자바로 작성된 템플릿 엔진입니다. 개발자는 HTML, XHTML 또는 HTML5 페이지 템플릿을 정의한 다음 나중에 데이터로 채워 최종 페이지를 생성 할 수 있습니다. 따라서 Model-View-Controller 패턴의 Model-View 부분을 구현합니다.
Thymeleaf의 중요한 디자인 원칙은 템플릿 자체가 제대로 작성 (HTML)되어야한다는 것입니다.
번역 | 날짜 | 최신 릴리스 | 날짜 |
---|---|---|---|
3.xx | 2016-05-08 | 3.0.6 | 2017-05-07 |
2.xx | 2012-02-09 | 2.1.5 | 2016-07-11 |
Jquery로 Ajax를 통해 양식을 제출하려면 다음을 수행하십시오.
<div id="yourPanel" th:fragment="yourFragment">
<form id="yourForm" method="POST"
th:action="@{/actions/postForm}"
th:object="${yourFormBean}">
<div class="form-group">
<label for="param1"></label>
<input class="form-component" type="text" th:field="*{param1}" />
</div>
<div class="form-group">
<label for="param2"></label>
<input class="form-component" type="text" th:field="*{param2}" />
</div>
<div class="form-group">
<label for="param3"></label>
<input class="form-component" type="checkbox" th:field="*{param3}" />
</div>
<button type="submit" class="btn btn-success">Save</button>
<a href='#' class="btn btn-default">Cancel</a>
</form>
</div>
<script th:inline="javascript">
/*<![CDATA[*/
$(document).ready(function () {
/*[+
var postUrl = [[@{/actions/postForm(
additionalParam=${#httpServletRequest.getParameter('additionalParam')}
)}]];
+]*/
$("#yourForm").submit(function (e) {
e.preventDefault();
$.post(postUrl,
$(this).serialize(),
function (response) {
var isErr = 'hasError';
// when there are an error then show error
if (response.indexOf(isErr) > -1) {
$("#yourPanel").html(response);
} else {
var formData = $("#yourForm").serializeArray(),
len = formData.length,
urlEnd = '';
for (i = 0; i < len; i++) {
urlEnd += formData[i].name + '=' + encodeURIComponent(formData[i].value) + '&';
}
/*[+
var urlReplacement = [[@{/another/page(
additionalParam=${#httpServletRequest.getParameter('additionalParam')}
)}]] + urlEnd;
+]*/
window.location.replace(urlReplacement);
}
}
);
return false;
});
});
/*]]>*/
</script>
YourFormBean 클래스 :
@lombok.Getter
@lombok.Setter
@lombok.NoArgsConstructor
public class YourFormBean {
private String param1;
private String param2;
private boolean param3;
}
컨트롤러 코드 :
@RequestMapping(value = "/actions/postForm", method = RequestMethod.POST)
public String saveForm(Model model,
@RequestParam("additionalParam") Integer additionalParam,
@Valid @ModelAttribute("yourFormBean") YourFormBean yourFormBean,
BindingResult bindingResult,
RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
model.addAttribute("hasError", true);
return "your/template :: yourFragment";
}
redirectAttributes.addAttribute("additionalParam", additionalParam);
return "redirect:/another/page";
}
Thymeleaf를 시작하려면 공식 다운로드 페이지를 방문 하십시오 .
Maven 의존성
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
Gradle dependency
compile group: 'org.thymeleaf', name: 'thymeleaf', version: '3.0.1.RELEASE'
구성 예
버전 3.0부터는 Thymeleaf는 Java 구성 만 지원합니다.
public ViewResolver viewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setCharacterEncoding("UTF-8");
resolver.setContentType("text/html; charset=UTF-8");
return resolver;
}
viewResolver()
메서드에서 뷰의 인코딩 및 내용 유형을 설정할 수 있습니다. 추가 정보
public TemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolver(templateResolver());
return engine;
}
templateEngine()
에서 사용자 정의 방언을 추가 할 수 있습니다. 예를 들어 Spring Security dialect를 추가하려면 다음과 같이 할 수 있습니다. engine.addDialect(new SpringSecurityDialect());
public ITemplateResolver templateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("/views/");
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
resolver.setCharacterEncoding("UTF-8");
return resolver;
}
templateResolver()
메소드에서 접두어와 접미어에 대한 setter를 살펴보십시오. 그것은 Thymeleaf에게 컨트롤러가 뷰를 반환 할 때마다 Thymeleaf가 webapp/views/
디렉토리에서 html로 이름을 찾아서 .html
접미사를 추가한다는 것을 알려줍니다.
예
@RequestMapping(value = "/")
public String homePage() {
return "foo/my-index";
}
Thymeleaf는 webapp/views/foo/
디렉토리에서 my-index.html
이라는 html을 찾을 것입니다. 위의 예제 구성에 따라.
양식 객체
package formSubmission;
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name= name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
제어 장치
package formSubmission;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class FriendsController {
@GetMapping("/friends")
public String friendForm(Model model) {
model.addAttribute("personForm", new Person());
return "friendsForm";
}
@PostMapping("/friends")
public String submissionResult(@ModelAttribute("personForm") Person person) {
return "result";
}
}
friendsForm.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Friend form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Friend Form</h1>
<form th:action="@{/friends}" th:object="${personForm}" method="post">
<p>Name: <input type="text" th:field="*{name}"/></p>
<p>Age: <input type="number" th:field="*{age}"/></p>
<p><input type="submit" value="Submit"/></p>
</form>
</body>
</html>
result.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Submission result</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>th:text="'My friend ' + ${personForm.name} + ' is ' + ${personForm.age} + ' years old'"</h1>
</body>
</html>
웹 사이트의 일부를 교체하려는 경우 아약스로 손쉽게 교체 할 수 있습니다.
선택한 값을 기반으로 콘텐츠를 대체하려는 website.html :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Index</title>
</head>
<body>
<select id="selection">
<option>Content 1</option>
<option>Content 2</option>
</select>
<div id="replace_div">
Content goes here
</div>
<!-- JQury from Google CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
//call function when page is loaded
getContent();
//set on change listener
$('#selection').change(getContent);
function getContent() {
//create url to request fragment
var url = /content/;
if ($('#selection').val() === "Content 1") {
url = url + "content1";
} else {
url = url + "content2";
}
//load fragment and replace content
$('#replace_div').load(url);
}
})
</script>
</body>
</html>
그리고 선택한 값을 기반으로 포함하려는 파편이있는 content.html :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<div th:fragment="content1">
This is Content 1
</div>
<div th:fragment="content2">
This is Content 2
</div>
</body>
</html>
마지막으로 Spring MVC ContentController.java :
@Controller
@RequestMapping("content")
public class ContentController {
@RequestMapping("")
public String loadContent() {
return "website";
}
@RequestMapping("content1")
public String getContent1() {
return "content :: content1";
}
@RequestMapping("content2")
public String getContent2() {
return "content :: content2";
}
}
컨트롤러의 예제 메서드
@RequestMapping(value = "/test")
public String showCheckbox(Model model) {
boolean myBooleanVariable = false;
model.addAttribute("myBooleanVariable", myBooleanVariable);
return "sample-checkbox";
}
보기 : sample-checkbox.html
<input
type="checkbox"
name="myBooleanVariable"
th:checked="${myBooleanVariable}"/>
th:name
을 checbox로 사용하지 말고 th:name
만 name