【问题标题】:@RestController does not return html with model@RestController 不返回带有模型的 html
【发布时间】:2020-10-03 06:34:43
【问题描述】:

我正在尝试使用 rest 和 Thymeleaf 实现 Spring Boot MVC 应用程序。 在我的控制器类中,我有如下内容:

@RestController
public class UserController {
    
    @Autowired
    private GetUserInfoSrv userSrv;;
    
    @RequestMapping("/") **OR** @GetMapping
    public String getAllUsers(Model model) {
    
    List<UserRep> listUser = userSrv.getAllUsersSvc(); //this is returning correct output
    model.addAttribute("userList", listUser);
    return "Index";
}

我没有得到 Index.html 中填充的值:

<tbody>
    <tr th:each="users : ${userList}">
        <td th:text="${users.id}" />
        <td th:text="${users.firstName}">First Name</td>
        <td th:text="${users.lastName}">Last Name</td>
        <td th:text="${users.email}">Email Id</td>
        </td> -->
    </tr>
</tbody>

如果我使用@Controller 注释而不是@RestController,我可以在页面上查看结果。 @RestController 不起作用的任何原因?我尝试在类级别以及@RestController 中的方法级别添加@RequestMapping / @GetMapping,但没有任何效果。

【问题讨论】:

    标签: spring-boot spring-restcontroller


    【解决方案1】:

    Restcontroller = 控制器 + ResponseBody

    因此,如果您放置响应控制器,那么它将在响应正文中发送数据。

    因此,如果您想返回网页,请改用控制器注释。

    difference between controller and restcontroller

    【讨论】:

      【解决方案2】:

      改变

      @RestController
      public class UserController {
          // ...
      }
      

      通过

      @Controller
      public class UserController {
          //...
      }
      

      为了便于理解,一般@RestController 用于生成 RESTful API,@Controller 用于带有表单绑定的 Spring MVC。

      【讨论】:

      • 感谢您的解释。这就是为什么我想知道为什么在调用 REST(通过邮递员)返回实体/表示对象而不是模板时会得到“TemplateInputException”。
      猜你喜欢
      • 2017-03-08
      • 1970-01-01
      • 2021-04-13
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      • 2020-11-14
      • 2017-10-28
      • 2018-11-27
      相关资源
      最近更新 更多