koushikkothagal / spring-security-jpa

Code for full Spring Security + JPA + MySQL tutorial: https://youtu.be/TNt3GHuayXs
181 stars 233 forks source link

Add thymeleaf dependency #6

Open Global-Manu-Man opened 3 years ago

Global-Manu-Man commented 3 years ago

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;
    }  
}
SamjuTheCoder commented 3 years ago

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;
    }  
}