Difference between @Controller and @RestController: @Controller and @RestController is not having much difference, its just a matter of convenience to use @ResponseBody with @Controller.
In simple way, we can understand like this:
Table of Contents
@RestController = @Controller + @ResponseBody
@Controller:
@ResponseBody annotation should be used for RequestMapping methods to render any outputs like json/xml etc.
Code Sample:
Here @ResponseBody annotation is used for getStringWithController() method.
[java]
@Controller
public class UserControllerWithoutRest {
@RequestMapping(value = “/samplejson”, method = RequestMethod.GET, produces = { “application/json”,
“text/json” }, consumes = MediaType.ALL_VALUE)
@ResponseBody
public String getStringWithController() {
String jsonStr = null;
ObjectMapper mapper = new ObjectMapper();
// to avoid serialization issue in browser
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
// to print in pretty way
mapper.enable(SerializationFeature.INDENT_OUTPUT);
// to exclude null from serialization
mapper.setSerializationInclusion(Include.NON_NULL);
User user = new User(“Rithvik”, “rithvik@mirthbees.com”);
try {
jsonStr = mapper.writeValueAsString(user);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonStr;
}
}
[/java]
If you are not annotating with @ResponseBody then you will come across the below error:
After adding @ResponseBody getting output like this:
@RestController:
By default @ResponseBody annotation is used, so we do not want to externally mention it.
Code Sample:
Here @ResponseBody is not used, because by default @Restcontroller activate @ResponseBody as well.
[java]
@RestController
public class UserController {
@RequestMapping(value = “/restsamplejson”, method = RequestMethod.GET, produces = { “application/json”,
“text/json” }, consumes = MediaType.ALL_VALUE)
public String getStringWithRestController() {
String jsonStr = null;
ObjectMapper mapper = new ObjectMapper();
// to avoid serialization issue in browser
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
// to print in pretty way
mapper.enable(SerializationFeature.INDENT_OUTPUT);
// to exclude null from serialization
mapper.setSerializationInclusion(Include.NON_NULL);
User user = new User(“Raghavendra”, “raghavendra@mirthbees.com”);
try {
jsonStr = mapper.writeValueAsString(user);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonStr;
}
}
[/java]
So the output is:
so in simple term,
@RestController = @Controller + @ResponseBody
So when you do not want to use @ResponseBody in method signature externally then you can go with @RestController.
Feel free to write your comments/thoughts/suggestions below. Thanks for reading this post!