Search code examples
spring-bootspring-mvcthymeleaf

Thymeleaf + Spring MVC + Rest


I don't understand, how to change @Controller to @RestController for RESTFull serivce, if html template linked with attributes that I get in ModelAndView

@Controller
public class MyController{

   @GetMapping("/index")
   public ModelAndView index(){
      return new ModelAndView("/index", name, userService.getUser().getName());
   }
}

and in thymeleaf template it's look like

<p th:text="'Hello, ' + ${name} + '!'" />

But I wanna go to index page, and in background get user name

@RestController
public class MyController{

   @GetMapping("/api/user")
   public String index(){
      return userService.getUser().getName();
   }
}

I can use ajax for update tag "p", but in this way it's nothing benefit of using thymeleaf, I can use jsp. So what the best way use thymeleaf with rest and is it rational?


Solution

  • I think the purpose of Thymeleafis for server-side rendering. Thymeleaf is a Java template engine for processing and creating HTML, XML, JavaScript, CSS, and text. When you are using JSON API and parse the JSON and use angular or any other client-side rendering framework for that. Thymeleaf with REST is not the approach.

    But if you want to use both ways like provide data to Thymeleaf and also provide REST services to other application follow below approach.

    @RequestMapping('/foobars')
    abstract class FoobarBaseController {
    
        @RequestMapping
        abstract listAll()
    }
    
    @Controller
    class FoobarHtmlController extends FoobarBaseController {
        @Override ModelAndView listAll() {
            new ModelAndView('foobars/foobarThymeleafTemplate', [foobars: foobarsList])
        }
    }
    
    
    
     @RestController
        @RequestMapping('/foobars', produces = MediaType.APPLICATION_JSON_VALUE)
    
    class FoobarJsonController extends FoobarBaseController {
        @Override Collection<Foobar> listAll() {
            foobarsList
        }
    }
    

    I hope this address your question properly.