JJJohn
JJJohn

Reputation: 1089

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

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?

Upvotes: 1

Views: 1094

Answers (1)

Nizam Mahammad
Nizam Mahammad

Reputation: 136

@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” and it will process the client request then, returns the view name as string format. e.g. a spring mvc web controller
  • The @RestController annotation primarly indicates that class is Restful web services, it return the data directly to the client in the JSON or XML format with help of @ResponseBody semantics by default so, i.e. servicing REST API.

Upvotes: 3

Related Questions