gpt4 book ai didi

java - 在 UI 端处理 ResponseEntity 的最佳方法是什么?

转载 作者:行者123 更新时间:2023-12-02 02:41:10 25 4
gpt4 key购买 nike

我有用户的页面,我必须在页面加载后显示他和他的 friend 撰写的所有帖子。在 UI 方面执行此操作的最简单方法是什么?我正在使用 Thymeleaf + Spring。

 @RequestMapping(method = RequestMethod.GET, path = "/getBasicPosts")
public ResponseEntity<Object> getUSerAndFriendsPosts(String userId) {
List<Post> postList;
try {
postList = postService.getUserAndFriendsPosts(Long.valueOf(userId));
} catch (Exception otherExc) {
return new ResponseEntity<>(otherExc.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(postList, HttpStatus.OK);
}

最佳答案

如果您使用 Thymeleaf + Spring,您的 Controller 必须返回 thymeleaf 模板的路径:

   @RequestMapping("/getBasicPosts/{userId}")
public String showBasicPosts(Model model, @PathVariable("userId") String userId) {
Object obj = getUSerAndFriendsPosts(String userId).getBody();
model.addAttribute("obj", obj);
return "path/of/template";
}

private ResponseEntity<Object> getUSerAndFriendsPosts(String userId) {
List<Post> postList;
try {
postList = postService.getUserAndFriendsPosts(Long.valueOf(userId));
} catch (Exception otherExc) {
return new ResponseEntity<>(otherExc.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(postList, HttpStatus.OK);
}

当然,您应该添加一些属性来告诉 Spring Thymeleaf 模板的位置:

@Bean
@Description("Thymeleaf Template Resolver")
public ServletContextTemplateResolver templateResolver() {
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");

return templateResolver;
}

@Bean
@Description("Thymeleaf Template Engine")
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.setTemplateEngineMessageSource(messageSource());
return templateEngine;
}

关于java - 在 UI 端处理 ResponseEntity 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57178776/

25 4 0