0

I am trying to implement Spring boot MVC application with rest and Thymeleaf. In my controller class I have something like below:

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

I am not getting the values populated in 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>

If I use @Controller annotation instead of @RestController, I am able to view the results on page. Any reason why @RestController does not work? I tried adding @RequestMapping / @GetMapping at class level as well as method level in @RestController but nothing works.

James Graham
  • 39,063
  • 41
  • 167
  • 242

2 Answers2

1

Restcontroller = Controller + ResponseBody

So if you put response controller then it will send the data in response body.

So use controller annotation instead if you want to return a web page.

See difference between controller and restcontroller

Alien
  • 13,439
  • 5
  • 35
  • 53
0

Change

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

by

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

For easy-to-understand, generally, @RestController for generate RESTful API, @Controller for Spring MVC with form binding.

James Graham
  • 39,063
  • 41
  • 167
  • 242
  • Thanks for the explanation. That is why I was wondering why I get 'TemplateInputException' when calling a REST (via postman) returning entity/representation object instead of template. – Lokesh Dau Oct 04 '20 at 06:36