[開発] Thymeleaf Quick Reference - Sample Codes

ThymeleafQuickReferenceApplication.java
package hoge;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SpringBootApplication
@Controller
public class ThymeleafQuickReferenceApplication extends WebMvcConfigurerAdapter {

  public static void main(String[] args) throws Exception {
    new SpringApplicationBuilder(Application.class).run(args);
  }

}

ThymeleafQuickReferenceController.java

package hoge.app.welcome;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import lombok.Data;

/**
* Handles requests for the application home page.
*/
@Controller
public class ThymeleafQuickReferenceController {

  private static final Logger logger = LoggerFactory.getLogger(ThymeleafQuickReferenceController.class);

  /**
   * Simply selects the home view to render by returning its name.
   */
  @RequestMapping(value = "/", method = { RequestMethod.GET, RequestMethod.POST })
  public String home(Locale locale, Model model) {
    logger.info("Welcome home! The client locale is {}.", locale);

    Date date = new Date();
    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

    String formattedDate = dateFormat.format(date);

    model.addAttribute("serverTime", formattedDate);

    return "welcome/home";
  }

  @GetMapping("/actionPath")
  public String dispItemList(Model model, HttpServletRequest request, @RequestParam("paramName") String varName) {
    // HTTP Headers --------------------
    Map<'String, String> httpHeaderMap = new HashMap<'String, String>();
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
      String key = (String) headerNames.nextElement();
      String value = request.getHeader(key);
      System.out.println(key + ":" + value);
      httpHeaderMap.put(key, value);
    }

    // String userName = request.getUserPrincipal().getName();

    ActionForm form = new ActionForm();
    List<'Item> itemList = new ArrayList<'Item>();// 項目一覧;
    Set<'String> itemGroupNameSet = new LinkedHashSet<'>();

    List<'Map<'String, Object>> queryResult = queryItemList();
    
    for (Map row : queryResult) {
      Item item = new Item();
      item.setId(Integer.parseInt(row.get("col_item_id").toString()));
      String itemGrpName = String.valueOf(row.get("col_item_grp_name"));
      item.setItemGrpName(itemGrpName);
      item.setItemName(String.valueOf(row.get("col_item_name")));
      item.setItemDisc(String.valueOf(row.get("col_item_disc")));
      item.setCurrentHogeCount(Integer.parseInt(row.get("col_cur_hoge_cnt").toString()));
      item.setTargetHogeCount(Integer.parseInt(row.get("col_tar_hoge_cnt").toString()));
      item.setHogePercent(String.valueOf(row.get("col_hoge_pcnt").toString()));
      item.setSelectedValue("1");
      itemGroupNameSet.add(itemGrpName);
    }
    form.setItemGroupNameSet(itemGroupNameSet);
    form.setItemList(itemList);
    model.addAttribute(form);
    return "thymeleafQuickReference";
  }

  private List<'Map<'String, Object>> queryItemList() {
    // TODO Auto-generated method stub
    return null;
  }

  public @Data class Item {
    int id;
    String itemGrpName;
    String itemName;
    String itemDisc;
    int currentHogeCount;
    int targetHogeCount;
    String hogePercent;
    String selectedValue;

    @Override
    public String toString() {
      String str =
          "itemName: " + itemName + "\n" +
          "itemDisc: " + itemDisc + "\n" +
          "currentHogeCount: " + currentHogeCount + "\n" +
          "";
      return str;
    }
  }
  
  public @Data class ActionForm {
    Set<'String> itemGroupNameSet;
    List<'Item> itemList;
    
  }
}

■ thymeleafQuickReference.html
<'!DOCTYPE html>
<'html xmlns:th="http://www.thymeleaf.org" lang="ja">

<'head>
<'!-- Required meta tags -->
<'meta charset="utf-8"><'/meta>
<'meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><'/meta>

  <'!-- Title -->
  <'title>Page Title<'/title>

<'!-- Bootstrap CSS
<'link rel="stylesheet" th:href="@{/css/bootstrap.min.css}" href="../../css/bootstrap.min.css" /> TBC -->
<'link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"/>

  <'!-- Page Original Styles -->
  <'!-- jQuery Read More/Less Toggle - A PEN BY Max (https://codepen.io/maxds/pen/jgeoA) -->

  <'style type="text/css">
  * {
    font-family: "Meiryo UI";
    color: #555;
    /* border: 1px solid navy; */
  }
  html, body{
    width:100%;
    height:100%;
  }
  .morecontent span {
    display: none;
  }
  .morelink {
    display: block;
  }
  <'/style>  
<'/head>
<'body>

<'!-- ============================================================ -->

<'form th:action="@{/actionPath}" method="post" th:object="${actionForm}">
<'input type="hidden" th:value="*{valFromSvr1}" name="valName1" />
<'input type="hidden" th:value="*{valFromSvr2}" name="valName2" />

<'!-- 固定ページヘッダ -->
<'nav class="navbar navbar-default navbar-fixed-top">
  <'div class="container-fluid">
    <'div class="navbar-header">
      <'a class="navbar-brand" href="#"><'span style="white-space: nowrap; font-size: x-large">
        <'img alt="logo" src="img/logo.png" style="height: 25px;"/>
        論理ページ名
      <'/span><'/a>
    <'/div>
    <'div class="collapse navbar-collapse">
      <'p class="navbar-text navbar-right" style="padding-right: 20px">
        ようこそ <'a href="#" class="navbar-link">ゲスト<'/a> さん | <'a th:href="@{/}" href="home.html" class="btn btn-outline-primary"> ホーム<'/a>
      <'/p>
    <'/div>
  <'/div>
  <'div class="container-fluid" style="font-size: large; padding-bottom: 10px;">
  ページ紹介文
   <'span class="label label-default">レベル1<'/span> <'span th:text="*{valFromSvr3}" style="font-weight: bold; color: crimson;"><'/span>日
  <'span th:if="!*{hasDone()}">
  <'!-- 処理未完時はsubmitボタンを表示する -->
     <'input type="submit" value="送信" class="btn-xs btn-primary"/>
  <'/span>
  <'/div>
<'/nav>

<'!-- ・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・ -->

<'div style="margin: 100px 20px 0px 20px; overflow-y: auto">

read more/less sample
<'span class="more">
ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ
<'/span>

<'div class="panel-group" id="sampleAccordion">
  <'!-- // アイテムグループブロック -->
  <'div class="panel panel-default" th:each="itemGrpName,itemGrpNameStat : *{itemGrpNameSetFromSvr}">
    <'div class="panel-heading">
      <'h3 class="panel-title">
        <'a data-toggle="collapse" data-parent="#sampleAccordion" th:href="'#accordionCollapse' + ${groupName}">
          <'!-- アイテムグループ名 -->
          <'h4 th:text="${itemGrpName}"><'/h4>
        <'/a>
      <'/h3>
    <'/div>
    <'div th:id="'accordionCollapse' + ${groupName}" class="panel-collapse collapse in">
      <'div class="panel-body">
        <'!-- // アイテムグループ別テーブル -->
        <'table class="table table-hover" style="width:100%;" th:each="item,rowStat : *{itemList}" th:if="${item.funcGrpName} == ${itemGrpName}">
          <'tbody>
            <'!-- // アイテム行 -->
            <'tr><'td>
              <'!-- // アイテム別詳細掲載テーブル -->
              <'table style="width:100%;">
                <'tbody>
                  <'tr>
                    <'!-- // アイテム見出し -->
                    <'td style="width:20%;">
                      <'!-- アイテム名 -->
                      <'h4 th:text="${item.itemName}"><'/h4>
                    <'/td>
                    <'td style="width:55%; ">
                      <'!-- // statusbar -->
                      <'div class="progress" style="margin-top: 24px; ">
                        <'div class="progress-bar" role="progressbar" th:style="'width: ' + ${item.hogePercent}+'%;'"><'!-- 獲得数比率 -->
                          <'span th:text="${item.currentHogeCount}" style="color: white;"><'/span><'!-- 獲得数 -->
                        <'/div>
                      <'/div>
                      <'!-- statusbar // -->

                    <'/td>
                    <'td style="width:10%; padding: 2px">
                      <'span class="label label-success" th:if="${item.hogePercent}==100" th:text="'達成'"><'/span>
                      <'span class="label label-default" th:if="${item.hogePercent}<100" th:text="'達成まであと'+${item.targetHogeCount-item.currentHogeCount}+'!'"><'/span>
                    <'/td>
                    <'!-- アイテム見出し // -->
                    <'td th:if="!*{hasDone()}" th:each="radioButton : *{radioButtons()}" rowspan="2" style="width:7%; text−align: center; padding: 10px;">
                      <'input type="radio" th:field="*{itemList[__${rowStat.index}__].selectedValue}" th:value="${radioButton.key}" />
                      <'label th:for="${#ids.next('selectedValue')}" th:text="${radioButton.value}"><'/label>
                    <'/td>
                  <'/tr>
                  <'tr>
                    <'td colspan="3">
                      <'!-- アイテム説明 -->
                      <'span class="more" th:text="${item.itemDisc}">
                      <'/span>
                    <'/td>
                  <'/tr>
                <'/tbody>
              <'/table>
              <'!-- アイテム別詳細掲載テーブル // -->
            <'/td><'/tr>
            <'!-- アイテム行 // -->
          <'/tbody>
        <'/table>
        <'!-- アイテムグループ別テーブル // -->
      <'/div>
    <'/div>
  <'/div>
  <'!-- アイテムグループブロック // -->
<'/div>

<'/div>
<'/form>
<'!-- ・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・ -->

<'div align="right">
  <'form th:action="@{/logout}" method="post"><'input type="submit" value="ログアウト"/><'/form>
<'/div>

<'!-- ============================================================ -->

  <'script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"><'/script>
  <'script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"><'/script>

  <'!-- js for read more/less -->
  <'script type="text/javascript">
  $(document).ready(function() {
    // Configure/customize these variables.
    var showChar = 50; // How many characters are shown by default
    var ellipsestext = "...";
    var moretext = "Show more >";
    var lesstext = "Show less";
    

    $('.more').each(function() {
      var content = $(this).html();
  
      if(content.length > showChar) {
        // disp ShowMore
        var c = content.substr(0, showChar);
        var h = content.substr(showChar, content.length - showChar);//content for hiding
  
        var html = c + '<'span class="moreellipses">' + ellipsestext+ ' <'/span><'span class="morecontent"><'span>' + h + '<'/span>  <'a href="" class="morelink">' + moretext + '<'/a><'/span>';

        $(this).html(html);
      }
  
    });
  
    $(".morelink").click(function(){
      if($(this).hasClass("less")) {
        $(this).removeClass("less");
        $(this).html(moretext);
      } else {
        $(this).addClass("less");
        $(this).html(lesstext);
      }
      $(this).parent().prev().toggle();
      $(this).prev().toggle();
      return false;
    });
  });
  <'/script>
<'/body>
<'/html>

tag : Thymeleaf Quick Reference Sample Codes

2017-09-17 08:59 : 開発 : コメント : 0 : トラックバック : 0 :
コメントの投稿
非公開コメント

« next  ホーム  prev »

search

ad



counter


tag cloud

category cloud