thymleaf预处理在调用实体get方法时返回null



我在thymeleaf中使用预处理,根据用户是否解决了一个挑战,在<i>中添加一个类。我正在使用一个方法isSolvedBy,它接受一个用户名字符串来检查用户是否解决了挑战。在模板中,用户名字符串通过调用另一个方法getUsername传递,该方法返回登录用户的用户名。调用getUsername()时方法,它将空值传递给调用函数。

控制器代码片段:

model.addAttribute("user", user.get());
model.addAttribute("score", user.get().getScore());
model.addAttribute("rank", user.get().getUserRank());
model.addAttribute("challenges", challengeList);
String challengesNumber = Integer.toString(challengeList.size());
model.addAttribute("challengesNumber", challengesNumber);
return "challenges";

挑战视图片段:

<a th:each="challenge: ${challenges}" th:href="@{/challenge(id=${challenge.challengeId})}" class="challenge-card white-text" style="text-decoration: none">
<h3 style="margin-top: 5px;" th:text="${challenge.challengeTitle}" class="golden-text"></h3>
<i th:classappend="${challenge.isSolvedBy(__${user.getUsername()}__)}"></i>  <!-- here is the preprocessing  -->
<div>
<h4 class="card-info">Points: <span class="golden-text" th:text="${challenge.challengeScore}"></span></h4>
<h4 class="card-info">Level: <span class="" th:text="${challenge.level}"></span></h4>
</div>
</a>

这就是挑战。isSolvedBy方法:

public String isSolvedBy(String username)
{
System.out.println(username);       // this prints null
return "solved-challenge";      // temporary return value
}

这个user.getUsername()方法:

public String getUsername() {
System.out.println(username);   // this prints the username value when called by thymeleaf

return username;
}

当控制器被调用时,一切工作正常,预处理语句"${challenge.isSolvedBy(__${user.getUsername()}__)}"被执行,没有任何错误,但它将一个空值传递给challenge.isSolvedBy()方法,即使user.getUsername()在被调用时实际上会打印实际的用户名。下面是实际输出:

2022-07-11 01:09:07.365  INFO 19416 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-07-11 01:09:07.365  INFO 19416 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2022-07-11 01:09:07.366  INFO 19416 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
yousef [printed from getUsername method]
null [printed from isSolvedBy method]
yousef [printed from getUsername method]
null [printed from isSolvedBy method]

我还在学习spring MVC和Thymeleaf,所以很明显我错过了一些东西,但我不知道它是什么。

有谁知道是什么问题吗?提前感谢。

似乎thyymleaf没有将__${user.getUsername()}__的返回值作为字符串传递。单引号是必需的,因为在第一次传入thymeleaf${challenge.isSolvedBy(__${user.getUsername()}__)}"${challenge.isSolvedBy(<result>)}的结果。我不知道为什么它传递它为空,没有抛出一个错误。正确的表达式应该包括需要作为字符串传递的表达式周围的',因为在编写像${challenge.isSolvedBy('__${user.getUsername()}__')}这样的预处理语句时,第一次thymeleaf传递后的结果将是${challenge.isSolvedBy('<result')},因此thymeleaf将结果作为字符串传递给方法。

最新更新