I recently started using Spring boot. I am trying to fetch the rows from the DB and trying to display the results on a webpage using the html file display.html.
In the control file, I have the following content:
package com.forms.demo.htmlExample.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.forms.demo.htmlExample.model.User;
import com.forms.demo.htmlExample.repo.UserRepository;
import com.forms.demo.htmlExample.service.UserService;
@Controller
public class IndexController {
@Autowired
private UserRepository repo;
@Autowired
private UserService service;
@RequestMapping("/displayUsers")
@ResponseBody
public String getUsers(Model model) {
List<User> users= service.getUsers();
model.addAttribute("users", users);
return "display";
}
My display.html (under the templates ) file is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Display</title>
</head>
<body>
<table>
</table>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
<tr th:each="usr:${users}">
<td th:text=${usr.fname}></td>
<td th:text=${usr.email}></td>
</tr>
</body>
</html>
However when I am sending the url http://localhost:8080/displayUsers, it is returning "display" instead of taking me to the page display.html.
Can anyone say what is going wrong here?
You are using @ResponseBody
in the getUsers
method of the IndexController
class, which is telling the Controller that object return should be serialized to JSON. In this case String "display" is getting serialized and returned as a String. Remove @ResponseBody from the getUsers method and return the view name as String as in the updated code:
@RequestMapping("/displayUsers")
public String getUsers(Model model) {
List<User> users= service.getUsers();
model.addAttribute("users", users);
return "display";
}