我开发了一个应用程序JAVA + Spring Boot + ThymeLeaf(简单易用的前端仅用于测试)。 我有简单的域类播放器:
@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;
}
我想在&#34; service&#34;中计算玩家年龄。类。
问题是:如何将这些信息传递给前端?
控制器方法如下所示:
@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对象(生日日期没有年龄)。
我不想存储每个玩家的数据库年龄值 - 很明显。
我应该向控制器添加另一个:model.addAttribute();有关年龄的信息? (即使对我来说它看起来也不好)
我正在寻找智能解决方案,遵守清洁代码和MVC的规则。 如果你能帮我找到好的解决方案,我很高兴,谢谢。
编辑: 我只创建了AgeCalculator类:
@Component
@Data
public class AgeCalculator {
public Integer calculateAge(Player player) {
return Years.yearsBetween(player.getBirthdayDate(), new LocalDate()).getYears();
}
}
修改后的控制器:
@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: Exception evaluating SpringEL expression: "ageCalculator.calculateAge(player.birthdayDate)"
我的代码出了什么问题?
答案 0 :(得分:1)
我首选的方法是向getAge()
类添加Player
方法。然后在前端,它看起来像这样:
<span th:text="${player.age}" />
如果您不想修改Player
类,可以使用calculateAge(LocalDate birthday)
方法创建一个帮助对象,然后将其添加到模型中并按以下方式调用它:
Java:model.addAttribute("helper", new BirthdayHelper());
Thymeleaf:<span th:text="${helper.calculateAge(player.birthdayDate)}" />
答案 1 :(得分:0)
您可以在javascript中添加完整对象或部分内容,并像纯值一样使用它:
<script type="text/javascript" th:inline="javascript">
/*<![CDATA[*/
var some_data =/*[[${data}]]*/;
/*]]>*/
</script>
这是将参数从spring控制器传递到前端的好方法。
答案 2 :(得分:0)
好的,谢谢你的所有重播。这个问题的完整解决方案。
控制器:
@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";
}
年龄计算器:
@Component
@Data
public class AgeCalculator {
private LocalDate fromStringToLocalDate(String localDateString) {
DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy");
return LocalDate.parse(localDateString, inputFormat);
}
public int calculateAge(String birthDate) {
if (birthDate != null) {
return Period.between(fromStringToLocalDate(birthDate), LocalDate.now()).getYears();
} else {
return 0;
}
}
}
玩家域类:
@Entity
@Setter
@Getter
@EqualsAndHashCode(exclude = {"events"})
public class Player {
(...)
private String birthdayDate;
}
Thymeleaf代码:
<p th:text="${ageCalculator.calculateAge(player.birthdayDate)}">Here will be a player age</p>