0

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!

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, but is there a way to explicitly use existing REST api endpoints, rather than using employeeService?
Well you can call other endpoints, but you would have to parse the JSON result and send it to your view, and it would look extreamly weird. Thats why you have your service, to avoid this code duplication of how to get your employees, it's really normal to have multiple enpoints like that. And yet, if you are worring about DB performance (many request, bla bla bla...) you can check @Cacheable annotation (spring.io/guides/gs/caching)
But if you still want to do it, stackoverflow.com/questions/52321463/… here you have it
Thanks, RestTemplate() seems to be what i needed. Whats bother me is that i need to pass (hardcoding) whole uri, like: htttp://localhost...bla bla bla, rather than somehow getting it from exiting restcontroller

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.