現在、Springbootを使用してカレンダーのWEBアプリを作成しています。
MainController
内で作成したカレンダーの要素をWeek
Classに渡しており、model.addAttribute
でweek.getWeekdays()
を使用して、Week
クラスから要素を全て受け取っている状態です。
ここからHTML側に要素を一つずつ表示したいのですが、以下画像の通り全ての要素が入った状態で表示されます。
現状、いい方法が思い浮かばないため
お手数ですが、現在記載しているソースコード以外に方法がありましたら、ご教示いただけますと幸いです。
MainController
package com.example.demo.controller;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import com.example.demo.entity.Week;
@Controller
public class MainController {
@GetMapping("/")
public String index(Model model) {
// カレンダーのインスタンス
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DATE);
// 今月の始まり
calendar.set(year, month, 1);
int startWeek = calendar.get(Calendar.DAY_OF_WEEK);
// 先月分の日数
calendar.set(year, month, 0);
int beforeMonthlastDay = calendar.get(Calendar.DATE);
// 今月分の日数
calendar.set(year, month + 1, 0);
int thisMonthlastDay = calendar.get(Calendar.DATE);
Week week = new Week();
int[] calday = new int[42]; // 最大で7日6週
List<Integer> weeklist = new ArrayList<>();
int count = 0;
// 先月分の日付を格納
for(int i = startWeek -2; i >= 0; i--) {
calday[count++] = beforeMonthlastDay -i;
}
// 今月分の日付を格納
for(int i = 1; i <= thisMonthlastDay; i++) {
calday[count++] = i;
}
// 翌月分の日付を格納
int nextMonthDay = 1;
while(count % 7 != 0) {
calday[count++] = nextMonthDay++;
}
int weekCount = count / 7;
for(int i = 0; i < weekCount; i++) {
for(int j = i * 7; j < i * 7 + 7; j++) {
if(calday[j] < 10) {
// System.out.println(calday[j]);
}else {
// System.out.println(calday[j]);
}
weeklist.add(calday[j]);
week.setWeekdays(weeklist);
}
}
model.addAttribute("weekday", week.getWeekdays());
System.out.println(week.getWeekdays());
return "index";
}
}
Week Class
package com.example.demo.entity;
import java.util.ArrayList;
import java.util.List;
public class Week {
private List<Integer> weekdays = new ArrayList<>();
public List<Integer> getWeekdays() {
return weekdays;
}
public void setWeekdays(List<Integer> weekdays) {
this.weekdays = weekdays;
}
}
index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>カレンダー</title>
</head>
<body>
<h1>カレンダー</h1>
<h3>2021年 8月</h3>
<table border="1" th:object="${weekday}">
<tr>
<td>日</td>
<td>月</td>
<td>火</td>
<td>水</td>
<td>木</td>
<td>金</td>
<td>土</td>
</tr>
<tr th:each = "i : ${#numbers.sequence(1,6)}">
<td th:each = "j : ${#numbers.sequence(1,7)}"><span th:text="${weekday}"></span></td>
</tr>
</table>
</body>
</html>