Monday, April 3, 2023

What is Spring MVC Controller? What is the role of @Controller in Spring MVC?

Spring MVC is one of the popular Java framework to develop web application. It is based upon Model View Controller design pattern, that's why Spring MVC. The Core Spring framework jsut provide dependency injection and container but its the Spring MVC which is responsible for routing requests, handling them and resolving to views. In last couple of article, I have taught you how Spring MVC works and the role of DispatcherServlet in Spring MVC framework and today, I'll explain about Spring MVC Controllers. Many Java developer think that DispatcherServlet is the controller in Spring MVC which is partially true. DispatcherServlet is Front Controller which means all request will go through it but it doesn't handle any request by itself, instead it delegates to Spring MVC controllers for further request processing. 

The Spring MVC Controllers are nothing but POJO which are annotated using @Controller annotation. The job of controller is to process the request and return the response. It generally return a logical view name and put the output inside Model object to be displayed by View object e.g. a JSP page. Model is nothing but a Map which is used by Spring MVC framework to loose couple Controllers from View. 

The @Controller annotation is also just for component scanning facility, so that Spring can automatically detect all controllers and register them, but it has nothing to do with request routing or handling. The big question is how Spring MVC finds which request goes to which controller? Answer to this question lies on handler mappings. 

The HandlerMapping interface, precisely (org.springframework.web.servlet.HandlerMapping) provides the abstraction for mapping requests to handlers. The HandlerMapping implementations inspect the request and come up with an appropriate controller. Spring MVC provides many built-in HandlerMapping implementations, and the most popular of them is the @RequestMapping annotation which is driven by RequestMappingHandlerMapping class. 

The @RequestMapping annotation can be used at method or class level and allows you to hook a method to a particular request. You can map request to handler method by using Path, Query Parameters, HTTP method, and presence of any HTTP header in the request. You can even map multiple web request to same handler methods inside controller. 



10 Points about Spring MVC Controllers

Now that you know what is a Spring MVC controller and what is the role of controller, let's learn and revise few important points about them. These point will not only help you to understand Spring MVC framework better but also encourage you to learn more about Spring MVC Controllers and the framework itself. 

1) Spring MVC controllers are POJO annotated with @Controller annotation e.g.

@Controller
public class AboutController{
....
}

2) The Controller class has methods which correspond to specific URLs, they are known as handler methods. There can be different handler methods to handle different requests including variants for different HTTP methods (GET, POST), query parameters provided etc.


3) Methods are mapped to URLs usually using annotations @RequestMapping, which can be used at class level or method level. The @RequestMapping annotation allows you to map a request to a Controller's handler method using URL path, Query Parameters, HTTP methods and presence of HTTP headers as shown below:

@Controller
@RequestMapping("/about")
public class AboutController {

 @RequestMapping(method=GET)
 public String about(){
 return "about";
 }
}


This method will be invoked when a GET request will hit the "/about" URL in the application. You can even map multiple URLs to same controller because @RequestMapping accept a String array. For example, @RequestMapping({"/about", "/contact"} will requests for both "/about" and "/contact" to the about() method of Controller class. 

4) The Spring MVC Controller fills Model with data, which is later provided to the View for rendering by DispatcherServlet. You can fill data into Model as shown below:

@RequestMapping(method=GET)
  public String about(Model model){
    model.addAttribute("email", "java@example.com");
   return "about";
}


5) In Spring MVC, Controller can directly return data by using @ResponseBody annotation without returning a view, mostly in case of RESTful Web Service. You can even annotate your controller using @RestController annotation to have @ResponseBody embedded to all methods. See REST with Spring course by Eugen Paraschiv for more information on how to develop RESTful application using Spring. 

For normal web application, Spring MVC controller can return a Logical view name as String. That is later resolved to a specific view using View Resolvers. For example, in out case logical view name returned by about() method is "about", which is resolved to"/WEB-INF/about.jsp" by using InternalResourceViewResolver, which applies prefix "/WEB-INF" and suffix ".jsp" to the logical view name. 

6) If Spring MVC controller returns null or return type is void, then the view name will be determined from the requested URL by removing leading slash and removing the extension using default RequestToViewNameTranslator class. 

7) In Controller's handler methods e.g. about(Model model), when specified as method parameters, certain objects are automatically injected by Spring framework to be used inside the controller methods e.g. Model, HttpServletRequest, HttpServletResponse, Locale, Principal, HttpSession, HttpEntity, TimeZone etc. 

What is Spring MVC Controller? What is the role of @Controller in Spring MVC?



8) Another good thing about Spring MVC Controller is that they can be well unit tested (is POJO) without container. From Spring 3.2, Spring MVC also provide several classes to mock Spring MVC and test a controller like you normally do e.g. by sending a GET request using web browser, but without using browser or web server. 

9) It's also worth remembering that just putting @RequestMapping annotation at class level is not enough, you still need to annotate handler method with @RequestMapping annotation. Any handler method in the Controller class without @RequestMapping annotation will be ignored. 

10) When you put @RequestMapping at the Controller class level and method level then the result is combination of two, instead of method level overriding the annotation defined at class level. For example if you have @RequestMapping("/about") at class level and another @RequestMapping(method=GET) at method level then that method will be invoked when a GET request will come for "/about" URL. 


That's all about what is Spring MVC Controller and what is their role in Spring MVC. As I said, they are just a normal POJO which are annotated with @Controller annotation. They contain handler methods which handles request. The mapping between request and handler method is defined using HandlerMapping object or @RequestMapping annotation. 

Spring MVC allows you to map a request to handler method using URL, Http method, HTTP header, and query parameters. You can even map multiple URL to same controller and same handler methods. 

Other Spring related articles you may like to explore this blog
  • 3 ways to learn Spring Framework better (article
  • 23 Spring MVC Interview questions for 2 to 3 years experienced (list)
  • What is the use of DispatcherServlet in Spring MVC? (answer)
  • 20+ Spring and REST Interview Questions (questions)
  • Difference between @Autowired and @Injection annotations in Spring? (answer)
  • 5 Free Spring and Spring Boot Courses to learn online (courses)
  • How to enable Spring security in Java application? (answer)
  • 13 Spring Actuator interview questions (spring actuator questions)
  • Does Spring certification help in Job and Career? (article)
  • Top 5 Spring Certification Mock Exams (list)
  • 10 Spring Annotation Java Developers Should Know (annotations)
  • 5 Spring and Hibernate online courses for Java developers (list)
  • 20 Spring Boot Testing Interview questions (Spring boot questions)
  • Top 5 Spring Boot Features for Java Developers (features)
  • 25 Spring Security Interview Questions (spring security questions)

Thanks for reading this article so far. If you like this article then please share with your friends and colleagues. If you have any question or feedback then please drop a comment and I'll try to find an answer for you.

P. S. - If you want to learn more about developing RESTful Web Services using Spring and Spring Security framework, I suggest you join Eugen Paraschiv's REST with Spring certification class. Eugen has some good real-world experience in developing and securing RESTful web services in Java and this class is a good opportunity to benefit from his immense experience.



No comments:

Post a Comment