Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a html page from a restful controller in spring boot?

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:

[enter image description here

like image 823
Gustavo Avatar asked Aug 01 '16 13:08

Gustavo


People also ask

CAN REST API return HTML?

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.

How do I return a view from RestController?

@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 .


2 Answers

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.

like image 84
kukkuz Avatar answered Sep 23 '22 13:09

kukkuz


Follow below steps:

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

  2. Replace the @RestController with @Controller

  3. Remove if you are using any view resolvers.

  4. Your controller method should return file name of view without extension like return "index"

  5. 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>` 
like image 42
Chandan Kumar Avatar answered Sep 23 '22 13:09

Chandan Kumar