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

时间:2019-07-24 08:44:10

标签: java html spring-boot spring-mvc thymeleaf

我有一个用户页面,其中必须显示该页面加载后由他和他的朋友撰写的所有帖子。在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);
    }

1 个答案:

答案 0 :(得分:0)

如果您使用Thymeleaf + Spring,则您的控制器必须返回百里香模板的路径:

   @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;
}