시그마 삽질==six 시그마

Thymeleaf 사용법 3탄 본문

프로그래밍/theamleaf

Thymeleaf 사용법 3탄

Ethan Matthew Hunt 2020. 4. 30. 10:07

HelloController

@RequestMapping("/")
@Controller
public class HelloController {

	@GetMapping("/")
	public String hello(Model model) {
		List<Person> list = Arrays.asList(
			new Person.Builder().name("정우성").age(30).height(180).car(Arrays.asList(new Car("소나타"), new Car("아반테"), new Car("넥소"))).build()
			, new Person.Builder().name("원빈").age(19).height(181).car(Arrays.asList(new Car("소나타"), new Car("아반테"), new Car("BMW"))).build()
			, new Person.Builder().name("이정").age(22).height(180).car(Arrays.asList(new Car("아반테"), new Car("그랜져"), new Car("페라리"))).build()
		);

		Map map = new HashMap<>();
		map.put("1", "람보르기니");
		map.put("2", "포르쉐");
		map.put("3", "부가티");
		map.put("4", "페라리");

		List numbers = new ArrayList();
		numbers.addAll(Arrays.asList(11,22,33,44,55));

		Person person = new Person.Builder().name("장동건").age(30).myPrecious(map).build();
		Car car = new Car("람보르기니",true);

		model.addAttribute("list", list);
		model.addAttribute("person", person);
		model.addAttribute("car", car);
		model.addAttribute("numbers", numbers);
		model.addAttribute("today", new Date());
		model.addAttribute("myFavorite", map);
		model.addAttribute("stringTest", "ㅎㅎㅎ");
		model.addAttribute("genders", Gender.values());

		return "hi";
	}

	@GetMapping("/test")
	public String hello2(Model model) {
		List<Person> list = Arrays.asList(
			new Person.Builder().name("정우성").age(30).height(180).car(Arrays.asList(new Car("소나타"), new Car("아반테"), new Car("넥소"))).build()
			, new Person.Builder().name("원빈").age(19).height(181).car(Arrays.asList(new Car("소나타"), new Car("아반테"), new Car("BMW"))).build()
			, new Person.Builder().name("이정").age(22).height(180).car(Arrays.asList(new Car("아반테"), new Car("그랜져"), new Car("페라리"))).build()
		);
		Person person = new Person.Builder().age(30).build();
		model.addAttribute("list", list);
		model.addAttribute("person", person);
		model.addAttribute("today", new Date());
		return "fm/go/test::cc";
	}

	@GetMapping("/main")
	public String index(Model model) {
		Person person = new Person.Builder().age(30).name("이동건").build();
		model.addAttribute("person", person);
		model.addAttribute("today", new Date());
		return "main";
	}
}

 

@Data
public class Car {
    String name;
    boolean used;

    public Car(String name) {
        this.name = name;
    }

    public Car(String name,boolean used) {
        this.name = name;
        this.used = used;
    }
}

@Getter
@AllArgsConstructor
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum  Gender {
	MALE("남자","men")
	, FEMALE("여자","woman");

	private  String korName;
	private  String engName;
}

//@Builder 사용안하고 만들어봄

@Data
public class Person {

    private String name;
    private int age;
    private int height;
    private String job;
    private List<Car> carList;
    private Map<Long, String> myPrecious;


    public Person(Builder builder) {
        this.name = builder.name;
        this.age = builder.age;
        this.height = builder.height;
        this.job = builder.job;
        this.carList = builder.carList;
        this.myPrecious=builder.myPrecious;
    }

    public static class Builder {
        private String name;
        private int age;
        private int height;
        private String job;
        private List<Car> carList;
        private Map<Long, String> myPrecious;

        public Builder name(String name) {
            this.name = name;
            return this;

        }

        public Builder job(String job) {
            this.job = job;
            return this;
        }

        public Builder age(int age) {
            this.age = age;
            return this;
        }

        public Builder height(int height) {
            this.height = height;
            return this;
        }

        public Builder car(List<Car> carList) {
            this.carList = carList;
            return this;
        }

        public Builder myPrecious(Map<Long,String> myPrecious) {
            this.myPrecious = myPrecious;
            return this;
        }

        public Person build() {
            return new Person(this);
        }
    }
}

 

 

application.yml

server:
  port: 8080

front:
  template: default
  api-server:
    prefix: http://localhost:8080/v1
  static:
    domain: http://localhost:${server.port}
    prefix: ${front.static.domain}/static/default

spring:
  thymeleaf:
    cache: false

 

관련 properties 는 요기

 

 

hi.html 코드

 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Hello Thymeleaf</title></head>
<body>

//sec 권한
<script type="text/javascript" th:inline="javascript">
		let a  = /*[[ ${xxx.hasAuthority('권한명')} ]]*/;
</script>

<select>
	<option
		th:each="orderStatus : ${orderStatus}"
		th:value="${orderStatus}" th:text="${rorderStatus.text}"
		th:unless="${orderStatus() == 'ORDERED'}">  //orderStatus가 ORDERED인건 빼고 보여줘라
	</option>
</select>

    <!--
    Simple expressions:
    Variable Expressions: ${...}
    Selection Variable Expressions: *{...}
    Message Expressions: #{...}
    Link URL Expressions: @{...}
    Fragment Expressions: ~{...}
    -->

    <b>th:block 사용시 태그가 안나옴:</b><br>
    <th:block th:text="'Test name: ' + ${person.name} + '님'"></th:block><br>

    <span th:text="'The name of the person is,' + ${person.name}+'!'"></span><br>
    <span th:text="|The name of the person is, ${person.name}!|"></span><br>

    <p>Hello, [[${person.name}]]!</p><br>
    Expressions between [[...]] or [(...)] are considered inlined expressions in Thymeleaf,
    and inside them we can use any kind of expression that would also be valid in a th:text or th:utext attribute.

    Note that, while [[...]] corresponds to th:text (i.e. result will be HTML-escaped),
    [(...)] corresponds to th:utext and will not perform any HTML-escaping.
    So with a variable such as msg = 'This is <b>great!</b>', given this fragment:


    <b>설정파일 가져오기:</b><br>
    <span th:text="${@environment.getProperty('front.static.prefix')}"></span><br>

    <b>파라미터 가져오기:</b>  http://localhost:8080/?username=%22%EC%9D%B4%EC%A0%95%EC%9E%AC%22 <br>
    param.username: <span th:text="${param.username}"></span><br>
    param.size():<span th:text="${param.size()}"></span><br>
    param.isEmpty():<span th:text="${param.isEmpty()}"></span><br>
    request.getParameter('username'):<span th:text="${#request.getParameter('username')}"></span><br>
    request.getAttribute('person'):<span th:text="${#request.getAttribute('person')}"></span><br>

    <b>select  box:</b><br>
    <select name="gender">
        <option th:each="gender,index : ${genders}"
                th:selected="${ gender.korName == '남자'}"
                th:text="${gender.korName}"
                th:value="${gender}">
               <!-- th:if="${gender.korName} == '남자'"
                th:if="${gender.korName=='남자'}"-->
        </option>
    </select><br>

    <b>each문 simple하게:</b><br>
    <div th:each="item : ${list}" th:text="${item.height}"></div><br>

    <b>list size:</b><br>
    <span th:text="${#lists.size(list)}"></span><br>
    11 가지고 있음: <span th:text="${#lists.contains(numbers, 11)}"></span><br>

    <b>map :</b><br>
    <ul
        th:if="${not #maps.isEmpty(person.getMyPrecious())}">
        <li class="text-align-left" th:each="name : ${person.myPrecious}" th:text="${name.value}"></li>
    </ul><br>


    Expression Basic Objects
    <!--
    #ctx: the context object.
    #vars: the context variables.
    #locale: the context locale.
    #request: (only in Web Contexts) the HttpServletRequest object.
    #response: (only in Web Contexts) the HttpServletResponse object.
    #session: (only in Web Contexts) the HttpSession object.
    #servletContext: (only in Web Contexts) the ServletContext object.
    -->
    Established locale country:
    <span th:text="${#ctx.locale}">US</span><br>
    <span th:text="${#ctx.request}">US</span><br>
    <span th:text="${#ctx.response}">US</span><br>
    <span th:text="${#ctx.session}">US</span><br>
    <span th:text="${#ctx.servletContext}">US</span><br>


    <!--Besides these basic objects, Thymeleaf will offer us a set of utility objects that will help us perform common tasks in our expressions.

    #execInfo: information about the template being processed.
    #messages: methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
    #uris: methods for escaping parts of URLs/URIs
    #conversions: methods for executing the configured conversion service (if any).
    #dates: methods for java.util.Date objects: formatting, component extraction, etc.
    #calendars: analogous to #dates, but for java.util.Calendar objects.
    #numbers: methods for formatting numeric objects.
    #strings: methods for String objects: contains, startsWith, prepending/appending, etc.
    #objects: methods for objects in general.
    #bools: methods for boolean evaluation.
    #arrays: methods for arrays.
    #lists: methods for lists.
    #sets: methods for sets.
    #maps: methods for maps.
    #aggregates: methods for creating aggregates on arrays or collections.
    #ids: methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
    You can check what functions are offered by each of these utility objects in the Appendix B.-->


    <b>"empty check"</b><br>
    <span th:text="${#lists.isEmpty(list)}">list not empty1</span><br>
    <div th:if="${not #strings.isEmpty(stringTest)}"> stringTest not empty </div>
    <div th:if="${list != null and !list.empty}"> list not empty2</div>

    <b>if문:</b><br>
    <span th:if="${person.name}=='장동건'" >
        <th:block th:text="'Test name: ' + ${person.name} + '님'"/>
    </span><br>



    <b>else 문:</b><br>
    <span th:unless="${person.name}=='이병현'" th:text="'age: ' + ${person.age} + '살'"></span><br>
    <span th:unless="${#lists.isEmpty(list)}"> ㅎㅎ</span><br>

    <b>3항 연산자</b><br>
    <span th:text="${person.job} ?: 'no user job '">...</span><br>
    <span th:text="${person.job} ?: _">no user job </span><br>
    <td th:text="${car.used}? '사용했다': '새차다'">car.isUsed</td><br>
    <td th:text="${car.used}? #{true} : #{false}">yes</td><br>

    <b>switch:</b><br>
    <td class="text-align-center" th:switch="${car.used}">
        <th:block th:case="true">노출</th:block>
        <th:block th:case="false">미노출</th:block>
    </td><br>

    <td th:switch="${#maps.size(person.myPrecious)}">
        <span th:case="'0'">NO Persons YET!</span>
        <span th:case="'1'" th:text="${person.myPrecious[0]}"></span>
        <div th:case="*">
            <div th:each="item:${person.myPrecious}" th:text="${item}"/>
        </div>
    </td>

    <b>boolean:</b><br>
    <td class="text-align-center" th:if="${car.used ==false}"> car.usered false </td>
    <td class="text-align-center" th:if="${car.used ==true}">  car.usered true</td>




    <b>대소 비교</b><br>
    <div th:if="${person.age} &gt; 20"> person.age 20 넘어</div><br>
    <span th:unless="${#lists.isEmpty(myList)}">List is not empty</span>


    <b>변수 정의(jstl set ):</b><br>
    <span th:with="myName=${person.name}">
         <span th:text="${myName}"></span>
    </span><br>

    <b>날짜:</b><br>
    <span th:text="${#calendars.format(today,'yyyy-MM-dd HH:mm:ss')}">13 february 2011</span></p><br>

    <!--implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5:3.0.4.RELEASE'-->
    <!--<span th:text="${#temporals.format(today,'yyyy-MM-dd HH:mm:ss')}">13 february 2011</span></p><br>-->

    <b>소스 링크:</b><br>
    <img th:src="@{https://img1.daumcdn.net/thumb/C428x428/?scode=mtistory2&fname=https%3A%2F%2Ftistory1.daumcdn.net%2Ftistory%2F3746022%2Fattach%2F7aae650c1ca646ea96cb3288cabfa437}"></img><br>


    <b>url 링크:</b><br>
    <td><a th:attr="href=${'/test/' + person.age}" th:text="${person.name}"></a></td><br>

    <!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=30&age=30' (plus rewriting) -->
    <a href="details.html" th:href="@{http://localhost:8080/gtvg/order/details(orderId=${person.age},age=${person.age})}">view1</a><br>

    <!-- Will produce '/order/details?orderId=30' (plus rewriting) -->
    <a href="details.html" th:href="@{/order/details(orderId=${person.age})}">view2</a><br>

    <!-- Will produce '/order/30/details' (plus rewriting) -->
    <a href="details.html" th:href="@{/order/{orderId}/details(orderId=${person.age})}">view3</a><br>




    <p>In two years, it will be <span th:text="2013 + 2"></span>.</p>

    <script th:inline="javascript">
        var username2 = /*[[${person.name}]]*/ "Gertrud Kiwifruit";
    </script>



    <!--<table border="1">
        <th>이름</th>
        <th>나이</th>
        <th>키</th>
        <th>자동차</th>
        <tr th:each="item : ${list}">
            <td th:text="${item.name}"></td>
            <td th:text="${item.age}"></td>
            <td th:text="${item.height}"></td>
            <td>
                <p th:each="car,status : ${item.carList}">
                    <span th:text="'index:'+${status.index}"></span>
                    <span th:text="'count:'+${status.count}"></span>
                    <span th:text="'current:'+${status.current}"></span>
                    <span th:text="'size:'+${status.size}"></span>
                    <span th:text="'even:'+${status.even}"></span>
                    <span th:text="'odd:'+${status.odd}"></span>
                    <span th:text="'first:'+${status.first}"></span>
                    <span th:text="'last:'+${status.last}"></span>
                    <span th:text="'name:'+${car.name}"></span>
                </p>
            </td>
        </tr>
    </table>-->

</body>
</html>

 

 

브라우저 출력

 

 

 

 

 

 

html 소스보기

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>Hello Thymeleaf</title></head>
<body>

    <!--
    Simple expressions:
    Variable Expressions: ${...}
    Selection Variable Expressions: *{...}
    Message Expressions: #{...}
    Link URL Expressions: @{...}
    Fragment Expressions: ~{...}
    -->

    <b>th:block 사용시 태그가 안나옴:</b><br>
    Test name: 장동건님<br>

    <span>The name of the person is,장동건!</span><br>
    <span>The name of the person is, 장동건!</span><br>

    <p>Hello, 장동건!</p><br>
    Expressions between ... or ... are considered inlined expressions in Thymeleaf,
    and inside them we can use any kind of expression that would also be valid in a th:text or th:utext attribute.

    Note that, while ... corresponds to th:text (i.e. result will be HTML-escaped),
    ... corresponds to th:utext and will not perform any HTML-escaping.
    So with a variable such as msg = 'This is <b>great!</b>', given this fragment:


    <b>설정파일 가져오기:</b><br>
    <span>http://localhost:8080/static/default</span><br>

    <b>파라미터 가져오기:</b>  http://localhost:8080/?username=%22%EC%9D%B4%EC%A0%95%EC%9E%AC%22 <br>
    param.username: <span>&quot;이정재&quot;</span><br>
    param.size():<span>1</span><br>
    param.isEmpty():<span>false</span><br>
    request.getParameter('username'):<span>&quot;이정재&quot;</span><br>
    request.getAttribute('person'):<span>Person(name=장동건, age=30, height=0, job=null, carList=null, myPrecious={1=람보르기니, 2=포르쉐, 3=부가티, 4=페라리})</span><br>

    <b>select  box:</b><br>
    <select name="gender">
        <option value="MALE" selected="selected">남자</option>
        <option value="FEMALE">여자</option>
    </select><br>

    <b>each문 simple하게:</b><br>
    <div>180</div>
    <div>181</div>
    <div>180</div><br>

    <b>list size:</b><br>
    <span>3</span><br>
    11 가지고 있음: <span>true</span><br>

    <b>map :</b><br>
    <ul>
        <li class="text-align-left">람보르기니</li>
        <li class="text-align-left">포르쉐</li>
        <li class="text-align-left">부가티</li>
        <li class="text-align-left">페라리</li>
    </ul><br>


    Expression Basic Objects
    <!--
    #ctx: the context object.
    #vars: the context variables.
    #locale: the context locale.
    #request: (only in Web Contexts) the HttpServletRequest object.
    #response: (only in Web Contexts) the HttpServletResponse object.
    #session: (only in Web Contexts) the HttpSession object.
    #servletContext: (only in Web Contexts) the ServletContext object.
    -->
    Established locale country:
    <span></span><br>
    <span></span><br>
    <span></span><br>
    <span>org.thymeleaf.context.WebEngineContext$SessionAttributesMap@6d56dd</span><br>
    <span></span><br>


    <!--Besides these basic objects, Thymeleaf will offer us a set of utility objects that will help us perform common tasks in our expressions.

    #execInfo: information about the template being processed.
    #messages: methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
    #uris: methods for escaping parts of URLs/URIs
    #conversions: methods for executing the configured conversion service (if any).
    #dates: methods for java.util.Date objects: formatting, component extraction, etc.
    #calendars: analogous to #dates, but for java.util.Calendar objects.
    #numbers: methods for formatting numeric objects.
    #strings: methods for String objects: contains, startsWith, prepending/appending, etc.
    #objects: methods for objects in general.
    #bools: methods for boolean evaluation.
    #arrays: methods for arrays.
    #lists: methods for lists.
    #sets: methods for sets.
    #maps: methods for maps.
    #aggregates: methods for creating aggregates on arrays or collections.
    #ids: methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
    You can check what functions are offered by each of these utility objects in the Appendix B.-->


    <b>"empty check"</b><br>
    <span>false</span><br>
    <div> stringTest not empty </div>
    <div> list not empty2</div>

    <b>if문:</b><br>
    <span >
        Test name: 장동건님
    </span><br>



    <b>else 문:</b><br>
    <span>age: 30살</span><br>
    <span> ㅎㅎ</span><br>

    <b>3항 연산자</b><br>
    <span>no user job </span><br>
    <span>no user job </span><br>
    <td>사용했다</td><br>
    <td>??true_ko??</td><br>

    <b>switch:</b><br>
    <td class="text-align-center">
        노출
        
    </td><br>

    <td>
        
        
        <div>
            <div>1=람보르기니</div>
            <div>2=포르쉐</div>
            <div>3=부가티</div>
            <div>4=페라리</div>
        </div>
    </td>

    <b>boolean:</b><br>
    
    <td class="text-align-center">  car.usered true</td>




    <b>대소 비교</b><br>
    <div> person.age 20 넘어</div><br>

    <b>변수 정의(jstl set ):</b><br>
    <span>
         <span>장동건</span>
    </span><br>

    <b>날짜:</b><br>
    <span>2020-09-19 16:13:51</span></p><br>

    <!--implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5:3.0.4.RELEASE'-->
    <!--<span th:text="${#temporals.format(today,'yyyy-MM-dd HH:mm:ss')}">13 february 2011</span></p><br>-->

    <b>소스 링크:</b><br>
    <img src="https://img1.daumcdn.net/thumb/C428x428/?scode=mtistory2&amp;fname=https%3A%2F%2Ftistory1.daumcdn.net%2Ftistory%2F3746022%2Fattach%2F7aae650c1ca646ea96cb3288cabfa437"></img><br>


    <b>url 링크:</b><br>
    <td><a href="/test/30">장동건</a></td><br>

    <!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=30&age=30' (plus rewriting) -->
    <a href="http://localhost:8080/gtvg/order/details?orderId=30&amp;age=30">view1</a><br>

    <!-- Will produce '/order/details?orderId=30' (plus rewriting) -->
    <a href="/order/details?orderId=30">view2</a><br>

    <!-- Will produce '/order/30/details' (plus rewriting) -->
    <a href="/order/30/details">view3</a><br>




    <p>In two years, it will be <span>2015</span>.</p>

    <script>
        var username2 = "\uC7A5\uB3D9\uAC74";
    </script>



    <!--<table border="1">
        <th>이름</th>
        <th>나이</th>
        <th>키</th>
        <th>자동차</th>
        <tr th:each="item : ${list}">
            <td th:text="${item.name}"></td>
            <td th:text="${item.age}"></td>
            <td th:text="${item.height}"></td>
            <td>
                <p th:each="car,status : ${item.carList}">
                    <span th:text="'index:'+${status.index}"></span>
                    <span th:text="'count:'+${status.count}"></span>
                    <span th:text="'current:'+${status.current}"></span>
                    <span th:text="'size:'+${status.size}"></span>
                    <span th:text="'even:'+${status.even}"></span>
                    <span th:text="'odd:'+${status.odd}"></span>
                    <span th:text="'first:'+${status.first}"></span>
                    <span th:text="'last:'+${status.last}"></span>
                    <span th:text="'name:'+${car.name}"></span>
                </p>
            </td>
        </tr>
    </table>-->

</body>
</html>

참고: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#standard-expression-syntax

'프로그래밍 > theamleaf' 카테고리의 다른 글

Thymeleaf 사용법 2탄(Thymeleaf Layout Dialect)  (0) 2020.04.29
Thymeleaf 사용법 1탄  (0) 2020.04.29
Comments