I want to return a simple html page from controller, but I get only the name of the file not its content. Why?
This is my controller code:
@RestController public class HomeController { @RequestMapping("/") public String welcome() { return "login"; } }
This is my project structure:
[
One of the core benefits of REST is its separation of representation (encoding) from the underlying resource being accessed. It's perfectly fine to return HTML if the client requests it as a preference via the Accept header.
@RestController is not meant to be used to return views to be resolved. It is supposed to return data which will be written to the body of the response, hence the inclusion of @ResponseBody .
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.
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>`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With