1. MVC is an abbreviation for a design pattern. What does it stand for and what is the idea behind it?
Model–View–Controller software architectural pattern is designed to decouple three components, each of them can be easily swapped with a different implementation, and together they provide a fully functional user interface.
Advantages:
Spring MVC Request Life Cycle
@RequestMappin
g annotation at the type or method level within controller classes.2. Do you need spring-mvc.jar in your classpath or is it part of spring-core?
3. What 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:
This servlet initializes a WebApplicationContext that is a child of root ApplicationContext.
Front controller pattern stands for a single servlet delegates responsibility for a request to other components of an application, to perform actual processing.
Following front controller pattern, Spring MVC provides DispatcherServlet
receiving all the requests and delegates the processing to request handlers (controllers). Once the processing is done, ViewResolver will render a view based on the view name.
A Spring web application may define multiple dispatcher servlets, each of which has its own namespace, its own Spring application context and its own set of mappings and handlers.
Used for
To enable Spring MVC within a web application
WebApplicationContext
Use Java to configure DispatcherServlet in the servlet container
public class DemoWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected String[] getServletMappings() { return new String[] { "/" }; // Map DispatcherServlet to / } @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[] { SecurityConfig.class, DataServiceConfig.class }; } @Override protected Class<?>[] getServletConfigClasses() { // Specify configuration class return new Class<?>[] { WebConfig.class }; } @Override protected Filter getServletFilters() { CharacterEncodingFilter cef = new CharacterEncodingFilter(); cef.setEncoding("UTF-8"); cef.setForceEncoding(true); return new Filter{ new HiddenHttpMethodFilter(), cef}; } }
To make things more practical, Spring class AbstractAnnotationConfigDispatcherServletInitializer
, an implementation of WebApplicationInitializer
, was extended because it contains concrete implementations of methods needed for the configuration of Spring web applications that use Java-based Spring configuration.
getRootConfigClasses()
: A root application context of type AnnotationConfigWebApplicationContext
will be created.getServletConfigClasses()
: A web application context of type AnnotationConfigWebApplicationContext will be createdgetServletMappings()
: The DispatcherServelt’s mappings (context) are specified by the array of strings returned by this method.getServletFilters()
: As the name of the methods says, this one will return an array of implementations of javax.servlet.Filter that will be applied to every requestBy providing an empty class that extends AbstractSecurityWebApplicationInitializer
, you are basically telling Spring that you want DelegatingFilterProxy
enabled, so springSecurityFilterChain
will be used before any other registered javax.servlet.Filter
.
AbstractAnnotationConfigDispatcherServletInitializer
will automatically be used to configure DispatcherServlet
and the Spring application context in the application’s servlet context.DispatcherServlet
and a ContextLoaderListener
.getServletMappings()
identifies one or more paths that DispatcherServlet will be mapped to. It will handle all requests coming into the application.getRootConfigClasses()
is called internally, and the configuration classes are used to create the root application context, which will become the parent ApplicationContext that contains bean definitions shared by all child (DispatcherServlet) contexts.In Spring Boot The spring-boot-starter-web starter by default configures DispatcherServlet to the URL pattern “/” and adds Tomcat as the embedded servlet container, which runs on port 8080. Spring Boot by default serves the static resources (HTML, CSS, JS, images, etc.) from the following CLASSPATH locations:
4. Is 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:
In short: the DispatcherServlet is not instantiated via an application context. It is instantiated before any application context is created. parent ApplicationContext is creted by ContextLoaderListener
, child ApplicationContext is created by Spring MVC DispatcherServlet
.
Spring MVC WebApplicationContext Hierarchy
Parent ApplicationContext
org.springframework.web.context.ContextLoaderListener
.Child ApplicationContext
DispatcherServlet
.We can have two DispatcherServlet instances in an application.
DispatcherServlet
can be instantiated in 2 different ways and in both it is initialized by the servlet container:
5. What is a web application context? What extra scopes does it offer?
WebApplicationContext is a Spring application context for web applications.
Comparing to ApplicationContext
WebApplicationContext
interface extends the ApplicationContext
interfaceIn addition to the standard Spring bean scopes singleton and prototype, there are three additional scopes available in a web application context:
ServletContext
The beans that are registered within the WebApplicationContext
can also access the Servlet Context by implementing the ServletContextAware
interface
public interface ServletContextAware extends Aware { void setServletContext(ServletContext servletContext); }
6. What is the @Controller annotation used for?
@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 a 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 implement the Controller interface and override handleRequest() method.
The core interface in Spring MVC is Controller. Spring simply requires that
The @EnableWebMvc
annotation enables the annotation support for Spring MVC, that is, the @Controller annotation.
The Dispatcher Servlet scans classes annotated with it to map the web requests to the methods annotated with @RequestMapping, which are mapped to a certain request URL
7. How is an incoming request mapped to a controller and mapped to a method?
When a request is issued to the application:
HandlerMapping
interface.8. What is the difference between @RequestMapping and @GetMapping?
@GetMapping
equals to ` @RequestMapping(method = RequestMethod.GET)`
9. What is @RequestParam used for?
The request parameter can be retrieved through a method argument annotated with @RequestParam
You can use the @RequestParam
annotation to bind Servlet request parameters.
By default, method parameters that use this annotation are required, but you can specify that a method parameter is optional by
@RequestParam
annotation’s required flag to false
orjava.util.Optional
wrapper.Type conversion is automatically applied if the target method parameter type is not String.
NB. use of @RequestParam
is optional. By default, any argument that is a simple value type (as determined by BeanUtils#isSimpleProperty) and is not resolved by any other argument resolver, is treated as if it were annotated with @RequestParam.
10. What are the differences between @RequestParam and @PathVariable?
@PathVariable
instructs Spring MVC to bind the path variable within the URL – for example, http:// localhost:8080/singer/1 into the id argument of the findSingerById() method. – Note that for the id argument, the type is Long, while Spring’s type conversion system will automatically handle the conversion from String to Long for us.
@RequestMapping(value = "/{userId}", method = RequestMethod.GET)
public String show(@PathVariable("userId") Long id, Model model) {
// ...
}
Differences:
http://localhost:8080/greeting?firstName=dammy&lastName=good
http://localhost:8080/firstname/dammy/lastname/good
11. What are some of the parameter types for a controller method?
12. What other annotations might you use on a controller method parameter? (You can ignore
form-handling annotations for this exam)
13. What are some of the valid return types of a controller method?
14. What is a View and what’s the idea behind supporting different types of View?
View is responsible for presenting the data of the application to the user.
The user interacts with the view.
The core view resolver provided by Spring is the InternalResourceViewResolver
; it is the default view resolver.
Inside spring-webmvc.jar
there is a file called DispatcherServlet.properties
, and in it all default infrastructure beans are declared.
Spring MVC provides several view resolvers to support multiple view technologies, such as JSP, Velocity, FreeMarker, JSF, Tiles, Thymeleaf, and so on.
supporting different types of views:
15. How is the right View chosen when it comes to the rendering phase?
View Resolution Sequence
DispatcherServlet
ViewResolvers
are asked in sequence (based on their Order)16. What is the Model?
17. Why do you have access to the model in your View? Where does it come from?
18. What is the purpose of the session scope?
A session-scoped Spring bean exists for the lifetime of a HTTP session.
This enables creating, for instance, a session-scoped Spring bean that contains a shopping cart.
The bean instance will remain the same during all requests the user makes within one and the same HTTP session.
19. What is the default scope in the web context?
Singleton Scope is default scope.
20. Why are controllers testable artifacts?
The goal of Spring MVC Test is to provide an effective way to test controllers by performing requests and generating responses through the actual DispatcherServlet.
The Spring MVC Test Framework also provide full Spring MVC runtime behavior for tests without running in a servlet container.
@RunWith(SpringRunner.class) @WebMvcTest(HomeController.class) public class HomeControllerTest { @Autowired private MockMvc mockMvc;// Injects MockMvc @Test public void testHomePage() throws Exception { mockMvc.perform(get("/")) .andExpect(status().isOk()) .andExpect(view().name("home")) .andExpect(content().string( containsString("Welcome to..."))); } }
21. What does a ViewResolver do?
ViewResolver
, that is a class implementing the ViewResolver interface, attempts to, given a view name and a locale, find a View.ViewResolver
attempts to map a view name to a View.InternalResourceViewResolver
; it is the default view resolver.@Configuration public class AppConfig { @Bean InternalResourceViewResolver viewResolver(){ InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/views"); resolver.setSuffix(".jspx" ); resolver.setRequestContextAttribute("requestContext"); return resolver; } }