我正在开发一个应用程序JAVA + Spring Boot + ThymeLeaf(简单且简单的前端仅用于测试)。 我有简单的域类 Player:
@Entity
@Setter
@Getter
@EqualsAndHashCode(exclude = {"events"})
public class Player {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String playerName;
private String playerLastName;
private String playerNickname;
private String playerEmailAddress;
private String playerTelephoneNumber;
@ManyToMany(mappedBy = "players", fetch = FetchType.EAGER)
private Set<Event> events = new HashSet<>();
@Enumerated(value = EnumType.STRING)
private FavouritePosition favouritePosition;
private LocalDate birthdayDate;
}
我想计算“服务”类别中的玩家年龄。
问题是:如何将这些信息传输到前端?
Controller 方法如下所示:
@RequestMapping("/event/{eventId}/player/{playerId}/show")
public String showPlayerForSpecificTeam(Model model, @PathVariable String eventId, @PathVariable String playerId) {
model.addAttribute("player", playerService.getPlayerByEventIdAndPlayerId(Long.valueOf(eventId), Long.valueOf(playerId)));
return "event/player/showPlayerForSpecifiedEvent";
}
方法getPlayerByEventIdAndPlayerId(Long.valueOf(eventId), Long.valueOf(playerId))
返回Player对象(没有年龄,只有生日日期)。
我不想在数据库中存储每个玩家的年龄值 - 这是显而易见的。
我应该向 Controller 添加另一个:model.addAttribute();有年龄信息吗? (即使对我来说也看起来不太好)
我正在寻找聪明的解决方案,遵守干净代码和 MVC 的规则。 如果您能帮助我找到好的解决方案,我将很高兴,谢谢。
编辑: 我刚刚创建了 AgeCalculator 类:
@Component
@Data
public class AgeCalculator {
public Integer calculateAge(Player player) {
return Years.yearsBetween(player.getBirthdayDate(), new LocalDate()).getYears();
}
}
修改后的 Controller :
@RequestMapping({"player/{playerId}/show"})
public String getPlayerById(Model model, @PathVariable String playerId) {
model.addAttribute("player", playerService.getPlayerById(Long.valueOf(playerId)));
model.addAttribute("ageCalculator", new AgeCalculator());
return "event/player/showPlayerById";
}
在 thymeleaf 中我使用:
<p th:text="${ageCalculator.calculateAge(player)}">Here will be a Player age</p>
但我收到错误:org.thymeleaf.exceptions.TemplateProcessingException:评估 SpringEL 表达式时出现异常:“ageCalculator.calculateAge(player.birthdayDate)”
我的代码有什么问题吗?
最佳答案
我的首选方法是添加 getAge()
方法Player
类(class)。那么在前端,它看起来像这样:
<span th:text="${player.age}" />
如果您不想修改 Player
类,您可以使用 calculateAge(LocalDate birthday)
创建一个辅助对象方法,然后将其添加到模型中并像这样调用它:
Java:model.addAttribute("helper", new BirthdayHelper());
thymeleaf :<span th:text="${helper.calculateAge(player.birthdayDate)}" />
关于java - 如何传递信息,反对thymeleaf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48407631/