controller, restcontroller, spring boot

Difference Between the @Controller and @RestController

Spring Framework introduced @Controller and @RestController annotations to create a controller. Basically, the controller is used to handling the client requests for a particular resource.

For example

mydomain.com/home

This request goes to dispatcher servlet then it will be forwarded to controller corresponding methods with that URL mapping

If you create your controller using @Controller annotation then your controller class methods must be resolve mapping URL with a view if they are not returning response.

@Controller
public class MyController{
@RequestMapping("/home")
public String home(){

return "home.jsp";
}

@RequestMapping("/welcome")
public ModelAndView welcome(){

ModelAndView mv=new ModelAndView("home.jsp");
mv.addObject("msg","welcome");
return mv;

}

}

Here home() method will resolve the respective view for  http://mydomain.com/home URL and welcome() method return model data which will be available on respective view home.jsp

@Controller is used to add a model object(which holds data) in your view but it can also be used as return only response( return data in JSON format).
for returning only response from controller class you have to write one more annotation @ResponseBody which basically convert your object to response.
you have to write @ResponseBody on your method to product only response.

@Controller
public class MyController{
@RequestMapping(value="/user")
@ResponseBody
public User getUser()

//reterival operations
return user;
}
}

But if you want to create Restful API then you have to annotate each method with @ResponseBody
That’s why spring 4.o introduced another annotation @RestController to create a controller.
if you create your controller using @RestController annotation then all methods of this controller class by default return response and you don’t need any more @ResponseBody annotation to return response from methods.

@RestController
public class MyController{
@RequestMapping(value="/user")
public User getUser()

//reterival operations
return user;
}
}



@Controller is a specialization of the @Component class and @RestController is a specialization of the @Controller

 

Leave a Reply