Tuesday, October 29, 2019

Spring Interview Questions - Basic To Advance - Part 3 Spring MVC

Which ViewResolver class is widely used?
The org.springframework.web.servlet.view.InternalResourceViewResolver class is widely used.


What is DispatcherServlet and ContextLoaderListener?
DispatcherServlet is the front controller in the Spring MVC application and it loads the spring bean configuration file and initialize all the beans that are configured. If annotations are enabled, it also scans the packages and configure any bean annotated with @Component, @Controller, @Repository or @Service annotations.
ContextLoaderListener is the listener to start up and shut down Spring’s root WebApplicationContext. It’s important functions are to tie up the lifecycle of ApplicationContext to the lifecycle of the ServletContext and to automate the creation of ApplicationContext. We can use it to define shared beans that can be used across different spring contexts.



What is ViewResolver in Spring?
ViewResolver implementations are used to resolve the view pages by name. Usually we configure it in the spring bean configuration file. For example:
          <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->

<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<beans:property name="prefix" value="/WEB-INF/views/" />

<beans:property name="suffix" value=".jsp" />

</beans:bean>

          <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<beans:property name="prefix" value="/WEB-INF/views/" />

<beans:property name="suffix" value=".jsp" />

</beans:bean>

InternalResourceViewResolver is one of the implementation of ViewResolver interface and we are providing the view pages directory and suffix location through the bean properties. So if a controller handler method returns “home”, view resolver will use view page located at /WEB-INF/views/home.jsp.

How to handle exceptions in Spring MVC Framework?
Spring MVC Framework provides following ways to help us achieving robust exception handling.
Controller Based – We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation.
Global Exception Handler – Exception Handling is a cross-cutting concern and Spring provides @ControllerAdvice annotation that we can use with any class to define our global exception handler.
HandlerExceptionResolver implementation – For generic exceptions, most of the times we serve static pages. Spring Framework provides HandlerExceptionResolver interface that we can implement to create global exception handler. The reason behind this additional way to define global exception handler is that Spring framework also provides default implementation classes that we can define in our spring bean configuration file to get spring framework exception handling benefits.

What are the minimum configurations needed to create Spring MVC application?
For creating a simple Spring MVC application, we would need to do following tasks.
Add spring-context and spring-webmvc dependencies in the project.
Configure DispatcherServlet in the web.xml file to handle requests through spring container.
Spring bean configuration file to define beans, if using annotations then it has to be configured here. Also we need to configure view resolver for view pages.
Controller class with request mappings defined to handle the client requests.
Above steps should be enough to create a simple Spring MVC application.

Can we send an Object as the response of Controller handler method?
Yes we can, using @ResponseBody annotation. This is how we send JSON or XML based response in restful web services.

Warning: “The type WebMvcConfigurerAdapter is deprecated”

This warning will appear if we're using Spring version 5 (or Spring Boot 2), either when upgrading an existing application or building a new application with the old API.

Let's briefly go through the history behind it.

In earlier versions of Spring, up to and including version 4, if we wanted to configure a web application, we could make use of the WebMvcConfigurerAdapter class:

@Configuration
public WebConfig extends WebMvcConfigurerAdapter {
   
    // ...
}
This is an abstract class that implements the WebMvcConfigurer interface and contains empty implementations for all the methods inherited.

By subclassing it, we can override its methods, which provide hooks into various MVC configuration elements such as view resolvers, interceptors and more.

However, Java 8 added the concept of default methods in interfaces. Naturally, the Spring team updated the framework to make full use of the new Java language features.

As mentioned, the WebMvcConfigurer interface, starting with Spring 5, contains default implementations for all its methods. As a result, the abstract adapter class was marked as deprecated.

Let's see how we can start using the interface directly and get rid of the warning:

@Configuration
public WebConfig implements WebMvcConfigurer {
    // ...
}

https://www.luckyryan.com/2013/02/07/migrate-spring-mvc-servlet-xml-to-java-config/


WebMvcConfigure is the replacement of applicationContext.xml

one needs to implement WebApplicationInitializer to get rid of web.xml or extends AbstractAnnotationConfigDispatcherServletInitializer

Example:

For bootstrapping the application.

public class MyWebApplicationInitializer
    extends AbstractAnnotationConfigDispatcherServletInitializer
{

    protected Class<?>[] getRootConfigClasses() {
        return new Class[] {RootConfig.class};
    }

    protected Class<?>[] getServletConfigClasses()  {
        return new Class[] {WebConfiguration .class};
    }

    protected String[] getServletMappings() {
        return new String[] {"/"};
    }

}

Ex #2
@Configuration
public class CustomDispatcherServlet implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        AnnotationConfigWebApplicationContext dispatcherServletContext = new AnnotationConfigWebApplicationContext();

        dispatcherServletContext.register(CustomDispatcherConfig.class);

        DispatcherServlet dispatcherServlet = new DispatcherServlet(dispatcherServletContext);

        // Create a servlet dynamically.
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", dispatcherServlet);

        dispatcher.setLoadOnStartup(1);

        // Add servlet mapping url. All url end with .html will be processed by this servlet.
        dispatcher.addMapping("*.html");
    }

What is a MultipartResolver and when its used?
MultipartResolver interface is used for uploading files – CommonsMultipartResolver and StandardServletMultipartResolver are two implementations provided by spring framework for file uploading. By default there are no multipart resolvers configured but to use them for uploading files, all we need to define a bean named “multipartResolver” with type as MultipartResolver in spring bean configurations.

Once configured, any multipart request will be resolved by the configured MultipartResolver and pass on a wrapped HttpServletRequest. Then it’s used in the controller class to get the file and process it

How to handle exceptions in Spring MVC Framework?
Spring MVC Framework provides following ways to achieve robust exception handling.

Controller Based – We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation.
Global Exception Handler – Exception Handling is a cross-cutting concern and Spring provides @ControllerAdvice annotation that we can use with any class to define our global exception handler.
HandlerExceptionResolver implementation – For generic exceptions, most of the times we serve static pages. Spring Framework provides HandlerExceptionResolver interface that we can implement to create global exception handler. The reason behind this additional way to define global exception handler is that Spring framework also provides default implementation classes that we can define in our spring bean configuration file to get spring framework exception handling benefits.

Spring MVC

How to validate form data in Spring Web MVC Framework?
Spring supports JSR-303 annotation based validations as well as provide Validator interface that we can implement to create our own custom validator. For using JSR-303 based validation, we need to annotate bean variables with the required validations.



What are Spring MVC Interceptor and how to use it?
Spring MVC Interceptors are like Servlet Filters and allow us to intercept client request and process it. We can intercept client request at three places – preHandle, postHandle and afterCompletion.

We can create spring interceptor by implementing HandlerInterceptor interface or by extending abstract class HandlerInterceptorAdapter.

The handler interceptor have to implement the HandlerInterceptor interface, which contains three methods :

preHandle() – Called before the handler execution, returns a boolean value, “true” : continue the handler execution chain; “false”, stop the execution chain and return it.
postHandle() – Called after the handler execution, allow manipulate the ModelAndView object before render it to view page.
afterCompletion() – Called after the complete request has finished. Seldom use, cant find any use case.

How do you load and inject properties into a Spring Bean?

Let’s say we have a message.properties file that defines a database connection timeout property called connection.timeout. To load this property into a Spring context, we need to define a propertyConfigurer bean:
 <bean id="propertyConfigurer" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
     <property name="location" value="/WEB-INF/message.properties" />
</bean>

After that we can use Spring Expression Language to inject properties into other beans:

<bean class="com.learningsolo.spring.ConnectionFactory">
     <property name="timeout" value="${connection.timeout}"/>
</bean>

The same is available in the annotation based configuration, like so:
@Value("${connection.timeout}")
private int timeout;

What are the different ways to configure a class as Spring Bean?
There are multiple ways to configure Spring Bean: XML configuration, Java based configuration and annotation based configuration.

XML configuration
<bean id="myBean" class="com.learningsolo.spring.MyBean"/>

Java Based Configuration
ConfigurableApplicationContext context;
context.getBeanFactory().registerSingleton(name, obj);

Annotation Based Configuration
A Spring Bean can be configured with the @Bean annotation, which is used together with @Configuration classes.

@Configuration
public class MyConfiguration {
    @Bean
    public MyService getService(){
        return new MyService();
    }
}

Annotations Based : Annotations @Component, @Service, @Repository and @Controller can also be used with classes to configure them as Spring Beans. In this case, the base package location has to be provided to scan for these classes, like so:
<context:component-scan base-package=”com.learningsolo.spring” />




No comments:

Post a Comment