Search code examples
springspring-bootmodel-view-controllerspring-restcontroller

Spring Boot - @RestController annotation gets picked up, but when replaced with @Controller annotation, it stops working


Here is a dummy project for the same :-

layout

BlogApplication.java

@SpringBootApplication
@RestController
public class BlogApplication {

    public static void main(String[] args) {
        SpringApplication.run(BlogApplication.class, args);
    }
    
    @GetMapping("/hello")
    public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
        return String.format("Hello %s!", name);
    }
    
}

HtmlController.java

@Controller  //does not work
OR
@RestController //works
public class HtmlController {

    @GetMapping("/getHtmlFile")
    public String getHtmlFile() {
        return "Bit Torrent Brief";
    }
}

Why is it that @RestController is able to map getHtmlFile but @Controller returns 404 when /getHtmlFile is hit?


Solution

  • @RestController is the combination of @Controller and @ResponseBody. when you use @Controller, you should write @ResponseBody before your method return type