質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.40%
Spring MVC

Spring MVCとは、Javaを用いてWebアプリケーションを開発できるフレームワーク。アーキテクチャにMVCを採用しており、画面遷移と入出力パラメータの受け渡しの基本的な機能の他、ユーザーの送信したパラメータに対する入力チェックなどさまざまな機能を持ちます。

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

Spring

Spring Framework は、Javaプラットフォーム向けのオープンソースアプリケーションフレームワークです。 Java Platform上に、 Web ベースのアプリケーションを設計するための拡張機能が数多く用意されています。

Thymeleaf

Thymeleaf(タイムリーフ)とは、Java用のテンプレートエンジンで、特定のフレームワークに依存せず使用することが可能です。

Spring Boot

Spring Bootは、Javaのフレームワークの一つ。Springプロジェクトが提供する様々なフレームワークを統合した、アプリケーションを高速で開発するために設計されたフレームワークです。

Q&A

解決済

1回答

352閲覧

spring と thymeleaf の連携(値を表示したい)

tetejiro

総合スコア17

Spring MVC

Spring MVCとは、Javaを用いてWebアプリケーションを開発できるフレームワーク。アーキテクチャにMVCを採用しており、画面遷移と入出力パラメータの受け渡しの基本的な機能の他、ユーザーの送信したパラメータに対する入力チェックなどさまざまな機能を持ちます。

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

Spring

Spring Framework は、Javaプラットフォーム向けのオープンソースアプリケーションフレームワークです。 Java Platform上に、 Web ベースのアプリケーションを設計するための拡張機能が数多く用意されています。

Thymeleaf

Thymeleaf(タイムリーフ)とは、Java用のテンプレートエンジンで、特定のフレームワークに依存せず使用することが可能です。

Spring Boot

Spring Bootは、Javaのフレームワークの一つ。Springプロジェクトが提供する様々なフレームワークを統合した、アプリケーションを高速で開発するために設計されたフレームワークです。

0グッド

0クリップ

投稿2024/06/14 16:36

編集2024/06/14 17:33

実現したいこと

以下の calendar.html 2行目の user.id を表示しようとするとエラーが出ます。
実現方法が分からないです。ご協力よろしくお願いします。
また、spring や thymeleaf のリファレンスにできる限り慣れていきたいと思っています。
回答する上で参考にしたリファレンスの該当箇所を教えていただけると、
自分で探し出すための参考になるため、大変嬉しいです。(まだリファレンスに慣れておらず、、余力があれば是非よろしくお願いいたします。)

HomeController.java で、model.addAttribute("frames", reservationInfos);で
データを渡しているところを、 for 文の繰り返し処理内で渡すということも考えましたが
Thymeleaf で上手いことやれるならそちらの方がいいのかなと思っております。
(全然実現方法は分からない状況ですが)

calendar.html

1<div th:each="frame : ${frames}" th:object="${frame}"> 2 <p th:text="'user_id ==> ' + *{user.id}"></p> 3 <p th:text="'Type ==> ' + *{type}"></p> 4 <p th:text="'予約した日 ==> ' + *{reserved_date}"></p> 5</div>

HomeController.java

1 @PostMapping("/calendar") 2 public String showCalendar(@Validated HospitalInfoForm form, BindingResult result, Model model) { 3 4 if (result.hasErrors()) { 5 return showIndex(form); 6 } 7 8 form.setDateTodayIfNull(); 9 List<UserReservationEntity> reservationInfos = service.getDateSchedule(form.hospital_id, form.date); 10 log.info("user_id ====> " + reservationInfos.get(0).user.id); 11 model.addAttribute("frames", reservationInfos); 12 model.addAttribute("hospitalName", service.getHospitalName(form.hospital_id)); 13 model.addAttribute("targetDate", form.date); 14 15 return "calendar"; 16 }

★★★★ 追記箇所 ★★★★

UserEntity.java

1@AllArgsConstructor 2public class UserEntity { 3 public int id; 4 public String name; 5 public String gender; 6 public LocalDate birthday; 7}

★★★★ 追記箇所 ★★★★

UserReservationEntity.java

1@Getter 2@AllArgsConstructor 3public class UserReservationEntity { 4 public UserEntity user; 5 public HospitalDateScheduleEntity schedule; 6 7 public String type; 8 public LocalDate reserved_date; 9 10 public int getUserId() { 11 return this.user.id; 12 } 13}

HospitalDateScheduleEntity.java

1@AllArgsConstructor 2public class HospitalDateScheduleEntity { 3 public int id; 4 public int hospital_id; 5 public LocalDate target_date; 6 public LocalTime target_time; 7}

↓いったんクエリせず、ベタ打ちでデータを作成しています。

ReservationInfoService.java

1@Service 2@RequiredArgsConstructor 3public class ReservationInfoService { 4 5 private final ReservationInfoRepository repository; 6 7 @Transactional 8 public String getHospitalName(int id) { 9 return repository.getHospitalName(id); 10 } 11 12 @Transactional 13 public List<UserReservationEntity> getDateSchedule(int hospital_id, LocalDate date) { 14// return repository.getTargetDateSchedule(hospital_id, date); 15 16 // 1.ユーザー生成 17 UserEntity user1 = new UserEntity(1, "harukaze", "woman", LocalDate.of(1995, 12, 5)); 18 UserEntity user2 = new UserEntity(2, "doncoco" , "man" , LocalDate.of(1990, 1, 2)); 19 UserEntity user3 = new UserEntity(3, "TomBrown", "man" , LocalDate.of(1980, 4, 19)); 20 UserEntity user4 = new UserEntity(4, "MORISANCHU", "woman", LocalDate.of(1980, 4, 19)); 21 UserEntity user5 = new UserEntity(5, "MINAMIKAWA", "man" , LocalDate.of(1980, 4, 19)); 22 23 // 2.予約枠生成 24 HospitalDateScheduleEntity frame1 = new HospitalDateScheduleEntity(1, 1, LocalDate.now(), LocalTime.of(10,0)); 25 HospitalDateScheduleEntity frame2 = new HospitalDateScheduleEntity(2, 1, LocalDate.now(), LocalTime.of(11,0)); 26 HospitalDateScheduleEntity frame3 = new HospitalDateScheduleEntity(3, 1, LocalDate.now(), LocalTime.of(12,0)); 27 HospitalDateScheduleEntity frame4 = new HospitalDateScheduleEntity(4, 1, LocalDate.now(), LocalTime.of(12,30)); 28 HospitalDateScheduleEntity frame5 = new HospitalDateScheduleEntity(5, 1, LocalDate.now(), LocalTime.of(14,30)); 29 30 // 3.予約枠に予約をセット 31 List<UserReservationEntity> reserveList = List.of( 32 new UserReservationEntity(user1, frame1, "200", LocalDate.now()), 33 new UserReservationEntity(null, frame1, "200", LocalDate.now()), 34 new UserReservationEntity(null, frame1, "200", LocalDate.now()), 35 new UserReservationEntity(null, frame1, "200", LocalDate.now()), 36 new UserReservationEntity(null, frame1, "200", LocalDate.now()), 37 new UserReservationEntity(user2, frame2, "400", LocalDate.now()), 38 new UserReservationEntity(null, frame2, "400", LocalDate.now()), 39 new UserReservationEntity(null, frame2, "400", LocalDate.now()), 40 new UserReservationEntity(null, frame2, "400", LocalDate.now()), 41 new UserReservationEntity(user3, frame3, "200", LocalDate.now()), 42 new UserReservationEntity(user4, frame4, "400", LocalDate.now()), 43 new UserReservationEntity(user5, frame5, "200", LocalDate.now()) 44 ); 45 46 return reserveList; 47 } 48}

発生している問題・分からないこと

エラー内容:Caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression
(User.id)

試したこと・調べたこと

  • teratailやGoogle等で検索した
  • ソースコードを自分なりに変更した
  • 知人に聞いた
  • その他
上記の詳細・結果

getter を付けてみるなどしましたが、未だ実現できておりません。

補足

id 'org.springframework.boot' version '3.2.6'
java : 21
lombok
thymeleaf

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

jimbe

2024/06/14 17:18

UserEntity はどのような定義になっているでしょうか。 また、 html で参照したいのは、 UserEntity の id フィールドでしょうか、それとも UserReservationEntity の getUserId メソッドでしょうか。
tetejiro

2024/06/14 17:45

いつも大変お世話になっております。 本当にありがとうございます。 UserEntity.java を追記いたしました。 >UserEntity の id フィールドでしょうか UserEntity の id フィールドです。 ID だけでなく、UserReservationEntity のレコードに紐づいている(UserReserveEntity に代入されている)UserEntity のメンバ変数全てを表示させたいと思っております。(id, name, gender, birth) getUserId メソッドは、試しに置いてみた途中のものがそのままになっておりました。 特に現在、使用しておりません。(紛らわしくしてしまい、申し訳ございません。)
jimbe

2024/06/15 18:57 編集

追加修正ありがとうございます。 例外のご提示が一部だけなので経緯がどうなっているか分かりませんが、私の手元の『springboot を使わず thymeleaf + SpringEL の (spring5 の) 環境』では、calendar.html の書き方でリスト内のオブジェクトのフィールド(user)のフィールド(id)の表示は出来ています。 ただしそれは user が null で無ければ、です。 null の場合は java で普通にあるように NullPointerException 的な例外になります。
tetejiro

2024/06/16 07:51

すみません。ありがとうございます。 私のEntityが null だったから、エラーをはいていたということに気づいていませんでした。 (お恥ずかしい限りです。。) 回答の方もいただき、誠にありがとうございます。 大変丁寧に書いていただき、恐縮です。 今の作業を急いでおりまして、回答の方は読むのに少しお時間いただきますが、 僭越ながら、ひとまずベストアンサーに選ばせていただき、読後 質問があればコメントにて質問をさせていただきたいと思っております。 改めまして、ご回答いただきまして誠にありがとうございました。
guest

回答1

0

ベストアンサー

素の Java プロジェクトで SpEL 式の Thymeleaf を使うまで を参考にサーバ等を使用しないでも SpEL を用いたテンプレート変換を試せるような環境を作ってテストしてみます。
(thymeleaf: 3.1.2, thymeleaf-spring5: 3.1.2, Spring-expression等: 5.3.37 で行いました。)

TestSpEL.java

java

1package teratail_java.q_3ayq7itkvjtrij; 2 3import java.time.LocalDate; 4import java.util.ArrayList; 5import java.util.List; 6 7import org.thymeleaf.context.Context; 8import org.thymeleaf.spring5.SpringTemplateEngine; 9import org.thymeleaf.templatemode.TemplateMode; 10import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; 11 12import lombok.AllArgsConstructor; 13 14public class TestSpEL { 15 public static void main(String[] args) { 16 17 ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver(); 18 resolver.setTemplateMode(TemplateMode.HTML); 19 resolver.setPrefix("template/"); 20 resolver.setSuffix(".html"); 21 22 SpringTemplateEngine templateEngine = new SpringTemplateEngine(); 23 templateEngine.setEnableSpringELCompiler(true); 24 templateEngine.setTemplateResolver(resolver); 25 26 //テストデータ 27 List<Reservation> list = new ArrayList<Reservation>(); 28 list.add(new Reservation(new User(1), "200", LocalDate.now())); 29 list.add(new Reservation(new User(2), "200", LocalDate.now())); 30 31 Context context = new Context(); 32 context.setVariable("frames", list); 33 34 System.out.println(templateEngine.process("index", context)); 35 } 36 37 @AllArgsConstructor 38 public static class Reservation { 39 public User user; 40 public String type; 41 public LocalDate reserved_date; 42 } 43 44 @AllArgsConstructor 45 public static class User { 46 public int id; 47 } 48}

index.html (calendar.html に "xmlns 属性を入れた html タグ" を追加したものです)

html

1<html xmlns:th="http://www.thymeleaf.org"> 2<div th:each="frame : ${frames}" th:object="${frame}"> 3 <p th:text="'user_id ==> ' + *{user.id}"></p> 4 <p th:text="'Type ==> ' + *{type}"></p> 5 <p th:text="'予約した日 ==> ' + *{reserved_date}"></p> 6</div> 7</html>

実行結果

<html> <div> <p>user_id ==&gt; 1</p> <p>Type ==&gt; 200</p> <p>予約した日 ==&gt; 2024-06-16</p> </div> <div> <p>user_id ==&gt; 2</p> <p>Type ==&gt; 200</p> <p>予約した日 ==&gt; 2024-06-16</p> </div> </html>

テストデータの二つ目 (29 行目) の user を null にしてみます。

list.add(new Reservation(null, "200", LocalDate.now()));

実行結果 (環境が違うため内容も異なるものと思いますが、例外が発生するという意味で同じと考えます。)

[main] ERROR org.thymeleaf.TemplateEngine - [THYMELEAF][main] Exception processing template "index": Exception evaluating SpringEL expression: "user.id" (template: "index" - line 3, col 8) org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "user.id" (template: "index" - line 3, col 8) at org.thymeleaf.spring5.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:292) (中略) at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1053) at teratail_java.q_3ayq7itkvjtrij.TestSpEL.main(TestSpEL.java:34) Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'id' cannot be found on null (後略)

投稿2024/06/15 19:33

編集2024/06/15 19:49
jimbe

総合スコア13045

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.40%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問