Home > Net >  It seems `@GetMapping` doesn't work with `@Controller`, why is that?
It seems `@GetMapping` doesn't work with `@Controller`, why is that?

Time:03-05

Per the doc, @RestController is just a convenience annotation which combines @Controller and @ResponseBody and @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET), which means @GetMapping should work well with both @RestController and @Controller

In fact @GetMapping only works with @RestController.

@RestController
public class HelloController {
  @GetMapping("/")
  public String hello(){
    return "hello";
  }
}

while

@Controller
public class HelloController {
  @GetMapping("/")
  public String hello(){
    return "hello";
  }
}

doesn't work.

I know I can use @RequestMapping(value = "/", method = RequestMethod.GET) instead, I'd just like to know why. Could someone give a clue?

CodePudding user response:

@Controller
public class TestController {
    
     @GetMapping("/")
     @ResponseBody
    public String hello() {
        return "hello";
    }
}

Add the @ResponceBody annotation then, it will work.

  • The @Controller annotation indicates that the class is a “Controller” e.g. a web controller
  • The @RestController annotation indicates that the class is a controller where @RequestMapping methods assume @ResponseBody semantics by default i.e. servicing REST API.
  • Related