Tuesday, November 13, 2018

Top 20 Spring MVC Interview Questions and Answers for 2 to 5 years Experienced Java Programmers

The Spring MVC framework is one of the most popular Java frameworks for developing web applications. If you have been working in Java and the developing web-based application then there is a good chance that you have already used Spring MVC in your project. In last decade, it has become the defacto framework for developing Java web application. Spring MVC is based on classic MVC (Model-View-Controller) design pattern but it is much more than that. It leverages, Spring framework's strength in terms of dependency injection and Inversion of control and promotes loosely coupled architecture, similar to the Spring framework itself. Because of its immense popularity and usefulness, most of the Java development job requires a good knowledge of Spring and Spring MVC.

There is a lot of demand for good Java developer with good knowledge and experience in Spring and Spring MVC. One way to prepare yourself for such job interviews is to look for good interview questions.

These questions not only help you to prepare well for interviews but also help you to understand the fundamental concepts better and encourage you to learn more by exploring and that's why I am always in search of good Spring MVC Interview questions.

Recently I was preparing for Spring Core Professional Certification when I come across some Spring certification guides from Pivotal. These guides contain some interesting questions on Spring MVC.

Even though these questions are provided just to give you an idea about the syllabus of Spring certification, I actually found many of such questions have already been asked to myself and friends in various Spring job interviews.

On request to a couple of my friends, I thought to share answers to these questions here. So, if you are preparing for either Spring Certification or Java Web Developer interview, you will find this list of Spring MVC Interview Questions very useful for your preparation.



20 Spring MVC Interview Questions for Java Programmers

Without further Ado, here is my list of some of the frequently asked Spring MVC questions from Java Interviews, particularly from the web development positions.


1. MVC is an abbreviation for a design pattern. What does it stand for and what is the idea behind it? (answer)
Answer - MVC is an abbreviation for Model-View-Controller design pattern. This pattern is based upon the separation-of-concerns design principle which promotes handling different functionality at different layer and loose coupling between layers.

In MVC pattern, Model contains the data which is rendered by View and Controler help in request processing and routing.

Neither Model knows about View, nor View is dependent upon Model, which means the same model can be rendered by different views e.g. JSP, FreeMarker or it can be even be written as JSON or XML in case of RESTful Web Services. You can learn more about MVC in my favorite course Spring Framework 5: Beginner to Guru. If you are serious about Spring, this is the course you should look.


Top 20 Spring MVC Interview Questions and Answers for 2 to 5 years Experienced



2. Do you need spring-mvc.jar in your classpath or is it part of spring-core? (answer)
The spring-mvc.jar is not part of spring-core, which means if you want to use Spring MVC framework in your Java project, you must include spring-mvc.jar in your application's classpath. In Java web application, spring-mvc.jar is usually placed inside /WEB-INF/lib folder.


3. What is the DispatcherServlet and what is it used for? (answer)
The DispatcherServlet is an implementation of Front Controller design pattern which handles all incoming web request to a Spring MVC application. A Front Controller pattern (see Enterprise application design pattern) is a common pattern in web applications whose job is to receive all request and route it to different components of application for actual processing.

In case of Spring MVC, DispatcherServlet route web requests to Spring MVC controllers.

In Spring MVC, DispatcherServlet is used for finding the correct Controler to process a request, which it does with the help of handler mapping e.g. @RequestMapping annotation.

It is also responsible for delegating logical view name to ViewResolver and then sending the rendered response to the client.


4. Is the DispatcherServlet instantiated via an application context? (answer)
No, DispatcherServlet is instantiated by Servlet containers like Tomcat or Jetty. You must define DispatcherServlet into the web.xml file as shown below.

You can see that load-on-startup tag is 1 which means DispatcherServlet is instantiated when you deploy Spring MVC application to Tomcat or any other Servlet container. During instantiation, it looks for a file servlet-name-context.xml and then initializes beans defined in this file.


5. What is the root application context in Spring MVC? How is it loaded? (answer)
In Spring MVC, the context loaded using ContextLoaderListener is called the "root" application context which belongs to the whole application while the one initialized using DispatcherServlet is actually specific to that servlet.

Technically, Spring MVC allows multiple DispatcherServlet in a Spring MVC web application and so multiple such contexts each specific for respective servlet but having same root context may exist. You can further check Introduction to Spring MVC course on Pluralsight to learn fundamentals of Spring like this.

Spring MVC Interview Questions and Answers

Btw, you would need a Pluralsight membership to access this course, which costs around $29 monthly or $299 annually. I have one and I also suggest all developers have that plan because Pluralsight is like NetFlix for Software developers.

It has more than 5000+ good quality courses on all latest topics. Since we programmers have to learn new things every day, an investment of $299 USD is not bad.

Btw, it also offers a 10-day free trial without any obligation which allows you to watch 200 hours of content. You can watch this course for free by signing for that trial.



6. What is the @Controller annotation used for? How can you create a controller without an annotation? (answer)
The @Controller is a Spring MVC annotation to define Controller but in reality, it's just a stereotype annotation. You can even create a controller without @Controller by annotating the Spring MVC Controller classes using @Component annotation. The real job of request mapping to handler method is done using @RequestMapping annotation.


7. What is the ContextLoaderListener and what does it do? (answer)
The ContextLoaderListener is a listener which helps to bootstrap Spring MVC. As the name suggests it loads and create ApplicationContext, so you don't have to write explicit code to do create it.

The application context is where Spring bean leaves. For a Web application, there is is a subclass called WebAppliationContext.

The ContextLoaderListener also tie the lifecycle of the ApplicationContext to the lifecycle of the ServletContext. You can get the ServletContext from WebApplicationContext using getServletContext() method.


8. What are you going to do in the web.xml? Where do you place it?
The ContextLoaderListener is configured in web.xml as listener and you put that inside a tag as shwon below:
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

When the Spring MVC web application is deployed, Servlet container created an instance of ContextLoaderListener class which loads the Spring's WebApplicationContext. You can also see Spring MVC For Beginners to learn more about ContextLoaderListener and WebApplicationContext and their role in Spring MVC.

Spring Interview Questions and answers



9. How is an incoming request mapped to a controller and mapped to a method? (answer)
Sometimes this question is also asked How does DispatcherServlet knows which Controller should process the request? Well, the answer lies in something called handler mappings.

Spring uses handler mappings to associate controllers with requests, two of the commonly used handler mappings are BeanNameUrlHandlerMapping and SimpleUrlHandlerMapping.

In BeanNameUrlHandlerMapping, when the request url matches the name of the bean, the class in the bean definition is the controller that will handle the request.

On the other hand, In SimpleUrlHandlerMapping, the mapping is more explicit. You can specify the number of URLs and each URL can be explicitly associated with a controller.

Btw, if you are using annotations to configure Spring MVC, which you should then @RequestMapping annotations is used to map an incoming request to a controller and a handler method.

You can also configure @RequestMapping annotation by URI Path, by query parameters, by HTTP methods of a request and by HTTP headers present in the request.


10. What is the @RequestParam used for? (answer)
The @RequestParam is a Spring MVC annotation which is used to extract request parameter or query parameters from URL in Controller's handler method as shown below:

public String personDetail(@RequestParam("id") long id){
  ....
  return "personDetails";
}

The @RequestParam annotation also supports data type conversion e.g. you can see here a String is converted to long automatically but it can also result in an exception if query parameter is not present or in case of type mismatch. You can also make the parameter optional by using requried=false e.g. @RequestParam(value="id", required=false )


11. What are the differences between @RequestParam and @PathVariable? (answer)
Even though both @RequestParam and @PathVariable annotations are used to extract some data from URL, there is a key difference between them.

The @RequestParam is used to extract query parameters e.g. anything after "?" in URL while @PathVariable is used to extract the part of the URI itself. For example, if the given URL is http://localhost:8080/SpringMVC/books/3232233/?format=json

Then you can access the query parameter "format" using @RequestParam annotation and /books/{id} using @PathVariable, which will give you 3232233.

Here is another example of @PathVariable,

@RequestMapping("/persons/{id}" )
public String personDetail (@PathVariable ("id" ) long id) {...}

This code can extract person id=123 from /persons/123. It is particularly used in RESTful Web Services because their id is usually part of URI or URL path.

Spring questions and answers



12. What are some of the valid return types of a controller method? (answer)
There are many return types are available for a controller method in Spring MVC which is annotated by @RequestMapping inside the controller. Some of the popular ones are:
  1. String
  2. void
  3. View
  4. ModelAndView (Class)
  5. Model (Interface)
  6. Map
  7. HttpEntity<?> or ResponseEntity<?>
  8. HttpHeaders


You can see the full list of valid return types for a Spring MVC controller here. http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-return-types

Every return type has its specific use. For example, if you are using String then it means Controller just return View Name and this view name will resolve by ViewResolver.

If you don't want to return any view name mention return type void. If you want to set view name as well as want to send some object use ModelAndView as a return type.


13. What is a View and what's the idea behind supporting different types of View? (answer)
A View is an interface in Spring MVC application whose implementations are responsible for rendering context and exposing the model. A single view exposes multiple model attributes. Views in Spring MVC can be beans also.

They are likely to be instantiated as beans by a ViewResolver. As this interface is stateless, view implementations should be thread-safe. by using ViewResolver, a logical name of view can be resolved into different types of View implementation e.g. JstlView for displaying JSP or other view implementations for FreeMarker and Velocity.

If you are new to Spring MVC and not familiar with these basic classes, then I suggest you learn Spring by joining one of the free Spring courses I have shared earlier.

Spring MVC Interview Questions and Answers for 2 to 5 years Experienced Java Programmers



14. How is the right View chosen when it comes to the rendering phase? (answer)
The right View is chosen by ViewResolver in Spring MVC. When Controller returns a logical view name to DispatcherServlet, it consults to ViewResolver to find the right View.

The ViewResolver depending upon its implementation resolves the logical view into a physical resource e.g. a JSP page or a FreeMarker template.

For example, InternalResourceViewResolver is a default view resolvers which converts logical view name e.g. "hello" to "/WEB-INF/hello.jsp" using prefix and suffix.


15. What is the Model? (answer)
Model is again a reference to encapsulate data or output for rendering. Model is always created and passed to the view in Spring MVC. If a mapped controller method has Model as a method parameter, then a model instance is automatically injected by Spring framework to that method.

Any attributes set on the injected model are preserved and passed to the View. Here is an example of using Model in Spring MVC:

public String personDetail(Model model) {
...
model.addAttribute("name", "Joe");
...
}

16. Why do you have access to the model in your View? Where does it come from? (answer)
You need to have access tot he model in your View to render the output. It's the model which contains the data to be rendered. The Model comes with the Controller, which process their client request and encapsulate the output into a Model object.


17. What is the purpose of the session scope? (answer)
The purpose of the session scope is to create an instance of the bean for an HTTP Session. This means the same bean can serve multiple requests if it is scoped in session. You can define the scope of a Spring bean using scope attribute or @Scope annotation in Spring MVC application.


18. What is the default scope in the web context? (answer)
The singleton scope is the default scope for a Spring bean even in the web context. The other three Web context-aware scopes are a request, session, and global-session, which are only available in a web application aware ApplicationContext object. See Spring Master Class - Beginner to Expert to learn more about ApplicationContext in Spring.

Spring MVC Interview Questions and Answers for Java developers


19. Why are controllers testable artifacts? (answer)
In Spring MVC Controllers are testable artifacts because they are not directly coupled with any View technology. They just return a logical View name, which can be easily tested.


20. What does the InternalResourceViewResolver do? (answer)
In Spring MVC, A ViewResolveer returns View to handle to output rendering based on the Logical View Name (provided by the controller) and locale. This way controller is not coupled to specific view technology e.g. JSP or FreeMarker it only returns the logical view name.

InternalResourceViewResolver is the default View resolver configured in Spring MVC and DispatcherServlet uses it to find the correct view. InternalResourceViewResolver is used to render JSPs (JstlView).

It Configures prefix and suffix to logical view name which then results in a path to specific JSP as shown below:
<bean class= "org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name= "prefix" value= "/WEB-INF/" />
<property name ="suffix" value =".jsp" />
</bean>

So if Controller returns "hello" as logical view name, the InternalViewResolver will return /WEB-INF/hello.jsp and DispatcherServlet will forward the request to this JSP page for rendering.

That's all about some of the frequently asked Spring MVC Interview Questions. If you know answers to these questions means you have good knowledge of Spring MVC framework, its different components e.g. DispatcherServlet, handler mappings, Controllers, Views and Model and can explain to anyone.

Sometime, you may get questions from Spring core and Spring security as well, hence it's also advisable to prepare for them. You can find some Spring Security Interview question here and Some Core Spring questions here.



Further Reading
Spring Framework 5: Beginner to Guru
Spring Master Class - Beginner to Expert
Spring Framework Interview Guide - 200+ Questions & Answers


Other Spring related articles you may like to explore this blog
  • 3 ways to learn Spring Framework better (article)
  • How Spring MVC works internally? (answer)
  • What is the use of DispatcherServlet in Spring MVC? (answer)
  • How to enable Spring security in Java application? (answer)
  • Does Spring certification help in Job and Career? (article)
  • How to prepare for Spring Certification? (guide)
  • 3 Best Practices Java Developers Can learn from Spring (article)
  • Difference between @Autowired and @Injection annotations in Spring? (answer)
  • 5 Spring and Hibernate online courses for Java developers (list)
  • 5 Spring Boot courses for Java developers (courses)
  • 5 courses to learn Microservices with Spring Boot and Spring Cloud (courses)

Thanks for reading this article. If you like these questions and my answers and explanations then please share with your friends and colleagues, it does make a difference. If you have any questions which are not answered in this list, feel free to drop a comment and I'll try my best to find an answer for you.

P.S. - If you want to learn how to develop RESTful Web Services using Spring Framework, check out Eugen Paraschiv's REST with Spring course. He has recently launched the certification version of the course, which is full of exercises and examples to further cement the real world concepts you will learn from the course.

No comments :

Post a Comment