Search code examples
javahtmlspring-bootwebspring-restcontroller

Return Html page using RestController in Spring Boot


I am trying to get the HTML page that I created. This is the structure of my project:

enter image description here

This is the "IndexController" class:

@RestController
@AllArgsConstructor
@RequestMapping(path = "/webpage")
public class IndexController {

        @GetMapping(path = {"mainpage"})
        @ResponseBody
        public String index(){
            return "Index";
        }
    
        @PostMapping("/check")
        public String CheckDataset(@ModelAttribute CheckModel checkModel){
            System.out.println(checkModel);
            return null;
        }
    
    }

When I open the HTML webpage directly from intellij:

enter image description here

Is opening perfectly, but when I am trying to open the HTML from Spring Boot is returning just the "Index" String.

Do you have any idea how to solve this?


Solution

  • Please note that your class IndexController shall not have @RestController if you need to show an HTML page. It shall only have @Controller.

    In simple terms @RestController = @Controller + @ResponseBody

    In your case, the @RestController annotation you used makes all the methods within it @ResponseBody by default, and you don't have to explicitly mention

    @ResponseBody annotation doesn't show the view instead it sends a String response.

    Steps to fix this issue:

    1. Change @RestController annotation to @Controller in class level
    2. Remove @ResponseBody from the method in which you're planning to show the HTML

    So your code will be

    @Controller
    @AllArgsConstructor
    @RequestMapping(path = "/webpage")
    public class IndexController {
    
        @GetMapping(path = {"mainpage"})
        public String index(){
            return "Index";
        }
    
       //Other methods
        
    }
    

    Just make sure you have spring-boot-starter-thymeleaf dependency in your POM.xml

    Thanks.