Nickname11
Nickname11

Reputation: 571

How to call Spring Boot RESt api using Spring MVC?

I have created REST api using Spring Boot. So, that is the fragment of it:

@RestController
@RequestMapping("/api/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @GetMapping(value = "/all", produces = "application/json")
    public ResponseEntity<List<Employee>> getAllEmployees() {
        return ResponseEntity.ok(employeeService.findall());
    }

Now, I would like to create more like MVC application part - simple view that shows all Employees using thymeleaf. (Just simple UI to use this app more convinient than sending curl requests)

@Controller
public class MainPageController {

    @GetMapping("/employees")
    public String showEmployees() {

        // i don't know what to do here

        return "employeesPage";
    }

What is the appropriate way to do so? Is there a more simple way to do it? Looking forward for your answers!

Upvotes: 0

Views: 1078

Answers (1)

Jordi
Jordi

Reputation: 387

So you do exactly the same you did on your EmployeeController but instead of a JSON, you return a view.

  • Get your employes through EmployeeService and put them on a collection
  • Create your employee view under /templates folder (many tutorials of how to do it)
  • return this view with your collection of employees

Example:

@GetMapping(value = "employees")
public ModelAndView showEmployees() {
    ModelAndView mav = new ModelAndView("employeesPage");
    mav.addObject("employees", employeeService.findall());
    return mav;
}

Check here for more detailed info: https://www.thymeleaf.org/doc/articles/springmvcaccessdata.html

Upvotes: 2

Related Questions