yash sachdeva
yash sachdeva

Reputation: 636

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?

Upvotes: 0

Views: 83

Answers (2)

Murat Kara
Murat Kara

Reputation: 831

@Controller
public class HtmlController {

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

This works.

Upvotes: 0

Mina Ramezani
Mina Ramezani

Reputation: 308

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

Upvotes: 2

Related Questions