spring-security-jpa icon indicating copy to clipboard operation
spring-security-jpa copied to clipboard

Add thymeleaf dependency

Open Global-Manu-Man opened this issue 3 years ago • 1 comments

The problem I had was How to return a html page from a restful controller in spring boot?

  1. Must put the html files in resources/templates/ or resources / public.

  2. Replace the @RestController with @Controller.

  3. Add dependency on thymeleaf.

  4. Remove if you are using any view resolvers.

  5. Your controller method should return file name of view without extension like return "index.html, user.html, admin.html".

  6. Add view name is: 'login.html' (full file name).

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

and

@RestController
public class MyRestController {
    @RequestMapping("/")
    public ModelAndView welcome() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login.html");
        return modelAndView;
    }  
}

Global-Manu-Man avatar Jul 26 '21 22:07 Global-Manu-Man

To my understanding and better clean code, I think doing it this way will give a clean code

@RestController
public class MyRestController {
    @RequestMapping("/")
    public ModelAndView welcome() {
        ModelAndView model = new ModelAndView();
        model.setViewName("login"); //removing  .html extension
        return model;
    }  
}

SamjuTheCoder avatar Aug 02 '21 15:08 SamjuTheCoder