How to return a html page from a restful controller in spring boot?
Follow below steps:
Must put the html files in resources/templates/
Replace the
@RestController
with@Controller
Remove if you are using any view resolvers.
Your controller method should return file name of view without extension like
return "index"
Include the below dependencies:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency>`
When using @RestController
like this:
@RestController
public class HomeController {
@RequestMapping("/")
public String welcome() {
return "login";
}
}
This is the same as you do like this in a normal controller:
@Controller
public class HomeController {
@RequestMapping("/")
@ResponseBody
public String welcome() {
return "login";
}
}
Using @ResponseBody
returns return "login";
as a String object. Any object you return will be attached as payload
in the HTTP body as JSON.
This is why you are getting just login
in the response.