1MVC is an abbreviation for a design pattern. What does it stand for and what is the idea behind it?

MVC stands for Model-View-Controller. The idea is to separate these three concepts rather than mixing them – as it is very hard to work when you have a view mixed with a controller and you need to change some details of the view.

2Do you need spring-mvc.jar in your classpath or is it part of spring-core?

I suppose the question is about spring-webmvc.jar and in that case you have to add it separately. 

3What is the DispatcherServlet and what is it used for?

DispatcherServlet is a front controller that receives all requests and delegates them to all the required controllers. But it is involved in more steps than just the first one. Among these are:

  • receiving the initial request and handling it to the required controller 
  • checking for the required controller using handler mappings
  • receiving the model and the view name from the controller and handling that to the required view after checking for that view with the view resolver (there are various types of resolvers for different view technologies – JSP, ThymeLeaf etc.)
  • calling the view resolver

This servlet initializes a WebApplicationContext that is a child of root ApplicationContext.

4Is the DispatcherServlet instantiated via an application context?

DispatcherServlet can be instantiated in 2 different ways and in both it is initialized by the servlet container:

  1. Defining it in XML, specifically in the web.xml of the project.
  2. Using Java – since Servlet 3.0 you can use the ServletContext.addServlet() method for registering the DispatcherServlet in ServletContext. This is Done in more ways; the one I like is extending AbstractAnnotationConfigDispatcherServletInitializer which allows you to specify the web configuration class and the root applicaiton class at one time.

5What is the root application context? How is it loaded?

A Spring MVC application usually has 2 application context – one for the web controllers etc. and another one for the “base” application components (services, data sources etc.).

The root application context is the parent context for any DispatcherServlet application contexts (that’s why it’s called root). The root application context is created by the ContextLoaderListener.

6What is the @Controller annotation used for? How can you create a controller without an annotation?

@Controller annotation is used to mark a class as a controller to be used by the DispatcherServlet to process requests. @Controller annotation is annotated by @Component so in case your DispatcherServlet creates an WebApplicationContext that is configured by component-scanning, that configuration will pick @Controller annotated classes automatically.

You can define controllers without component-scanning and in that case you will have to implements the Controller interface and override handleRequest() method.

7What is the ContextLoaderListener and what does it do?

ContextLoaderListener is a servlet container listener that creates a WebApplicationContext (root context) and adds it to the ServletContext of the web application. If beans from that context implement ServletContextAware those beans gain access to the ServletContext of the web-app.

8What are you going to do in the web.xml. Where do you place it?

web.xml is a deployment descriptor – meaning it is used by the web server to know how to serve the requests for the web application. web.xml must be placed in WEB-INF folder. This file describes the classes, resources and configuration of the application. (check https://cloud.google.com/appengine/docs/standard/java/config/webxml)

9How is an incoming request mapped to a controller and mapped to a method?

A @Controller annotated class may have a mapping annotation and it will be appended to the Dispatcher scans @Controller annotated classes for @RequestMapping annotated methods and those methods customize the model and return a view name for the response to be parsed for the user.

10What is the @RequestParam used for?

@RequestParam bind request parameters to mapping method’s parameters.

@Controller
public class IndexController {
    @RequestMapping(path = "/view")
    public String getIndex(@RequestParam String viewName) {
        return viewName;
    }
}

When calling the controller from above like http://localhost:9080/view?viewName=index index view will be returned.

@RequestParam makes the annotated parameter mandatory, to disable this behavior you need to add the required=false attribute to the annotation. If you annotate a Map parameter it will collect all the passed parameters to that variable. You can iterate over them in the JSP.

11What are the differences between @RequestParam and @PathVariable?

@PathVariable gets mapping method parameters from the URI itself whilst @RequestParam gets them from URI parameters.

for @PathVariable: http://www.foo.com/user/33

for @RequestParam: http://www.foo.com/user?id=33

package blog.codingideas.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {
    @RequestMapping(path = "/user/{id}")
    public String getIndex(@PathVariable int id, Model model) {
        model.addAttribute("userId",id);
        return "index";
    }
}
<html>
<head>
    <title>$Title

lt;/title>
</head>
<body>
User id: <c:out value="${userId}"/>
</body>
</html>

12What are some of the valid return types of a controller method?

  • A ModelAndView object, with the model implicitly enriched with command objects and the results of @ModelAttribute annotated reference data accessor methods.
  • A Model object, with the view name implicitly determined through a RequestToViewNameTranslator and the model implicitly enriched with command objects and the results of @ModelAttribute annotated reference data accessor methods.
  • A Map object for exposing a model, with the view name implicitly determined through a RequestToViewNameTranslator and the model implicitly enriched with command objects and the results of @ModelAttribute annotated reference data accessor methods.
  • A View object, with the model implicitly determined through command objects and @ModelAttribute annotated reference data accessor methods. The handler method may also programmatically enrich the model by declaring a Model argument (see above).
  • A String value that is interpreted as the logical view name, with the model implicitly determined through command objects and @ModelAttribute annotated reference data accessor methods. The handler method may also programmatically enrich the model by declaring a Model argument (see above).
  • void if the method handles the response itself (by writing the response content directly, declaring an argument of type ServletResponse / HttpServletResponse for that purpose) or if the view name is supposed to be implicitly determined through a RequestToViewNameTranslator (not declaring a response argument in the handler method signature).
  • If the method is annotated with @ResponseBody, the return type is written to the response HTTP body. The return value will be converted to the declared method argument type using HttpMessageConverters.
  • An HttpEntity<?> or ResponseEntity<?> object to provide access to the Servlet response HTTP headers and contents. The entity body will be converted to the response stream using HttpMessageConverters.
  • An HttpHeaders object to return a response with no body.
  • A Callable<?> can be returned when the application wants to produce the return value asynchronously in a thread managed by Spring MVC.
  • A DeferredResult<?> can be returned when the application wants to produce the return value from a thread of its own choosing.
  • A ListenableFuture<?> or CompletableFuture<?>/CompletionStage<?> can be returned when the application wants to produce the value from a thread pool submission.
  • A ResponseBodyEmitter can be returned to write multiple objects to the response asynchronously; also supported as the body within a ResponseEntity.
  • An SseEmitter can be returned to write Server-Sent Events to the response asynchronously; also supported as the body within a ResponseEntity.
  • A StreamingResponseBody can be returned to write to the response OutputStream asynchronously; also supported as the body within a ResponseEntity.
  • Any other return type is considered to be a single model attribute to be exposed to the view, using the attribute name specified through @ModelAttribute at the method level (or the default attribute name based on the return type class name). The model is implicitly enriched with command objects and the results of @ModelAttribute annotated reference data accessor methods.

13What is a View and what’s the idea behind supporting different types of View?

View is the base interface for different view technologies (XML, PDF, XLS etc.) Model data is passed to the view and rendered for providing different appearance. For passing the model data from controller to the view a view resolver is required – which also come in different flavours, that is different resolvers for different view types.

14How is the right View chosen when it comes to the rendering phase?

The right view is chosen by the ViewResolver bean that has to be registered in the container.

15What is the Model?

Model is a map of attributes passed by the controller to the view.

16Why do you have access to the model in your View? Where does it come from?

Model is created by the Controller and passed back to the DispatcherServlet which in turn checks with the ViewResolver where the Model should be passed to and then passes it to the required View. So basically the Model comes from DispatcherServlet

17What is the purpose of the session scope?

Session scope is required for isolating life cycle of a bean by a session. Suppose you have a e-shop, your e-shop basket shall have a session scope as users will need to be able to add goods from multiple requests (check https://dzone.com/articles/using-http-session-spring).

18What is the default scope in the web context?

In any context the default bean scope is singleton.

19Why are controllers testable artifacts?

Controller classes instances can be tested easily using MockMVC. It allows you to make calls of the required type to the controller and assert the response and other parameters.

20What does the InternalResourceViewResolver do? 

InternalResourceViewResolver allows you to resolve views (usually JSP) that are internal resources to the application.

@Bean
public ViewResolver viewResolver(){
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".jsp");
    return resolver;
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.