Spring controller gets invoked but returns 404
Short version:
Annotate your endpoint method with ResponseBody to bind the return value to the response body.
@Controller
public class MessageRequestController {
@RequestMapping(method = RequestMethod.GET, value = "/hello", produces = "application/json")
@ResponseBody
public String hello() {
System.out.println("Hit me!");
return "Hello, you!";
}
}
You can instead annotate your class with RestController instead of Controller
to apply ResponseBody
to each method of the class.
@RestController
public class MessageRequestController {
@RequestMapping(method = RequestMethod.GET, value = "/hello", produces = "application/json")
public String hello() {
System.out.println("Hit me!");
return "Hello, you!";
}
}
With @Controller, you use the default model-view from Spring Web MVC, and you're actually telling spring to render the view called Hello, you!.tml
from your resources directory (src/main/resources/templates
for a Spring Boot project, if I remember correctly).
You can read this article for more information about the Spring MVC REST Workflow.
Once you're more familiar with those concepts, you can even further customize your endpoint method using ResponseEntity.
As you see the "hit me", there's no mapping issue, but in your @RequestMapping annotation you specifie a produce type to "application/json" and you return a simple poor String not formatted and without any header('Content-Type: application/json').
Add the header and format the outpout.
Change your method return a ResponseEntity<T>
@RequestMapping(method = RequestMethod.GET, value = "/hello", produces = "application/json")
public ResponseEntity<String> hello() {
System.out.println("Hit me!");
return new ResponseEntity<String>("Hello, you!", HttpStatus.OK);
}
or change the controller to RestController
@RestController
public class MessageRequestController {...}
CURL
ubuntu:~$ curl -X GET localhost:8080/hello
Hello, you!