WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Spring Framework · Intermediate · question 33 of 100

What is the role of ViewResolver in Spring MVC?

📕 Buy this interview preparation book: 100 Spring Framework questions & answers — PDF + EPUB for $5

In the Spring MVC framework, the ViewResolver is responsible for resolving the view names returned by the controller and returning the corresponding view object.

The ViewResolver serves as an interface between the controller and the view. When the controller’s job is done, it returns the name of the view that should be used to render the output. The ViewResolver is then responsible for determining the actual view implementation to use based on the view name.

The ViewResolver interface requires implementing two methods:

1. ‘resolveViewName(String viewName, Locale locale)‘ - This method is responsible for resolving the view name to an actual view implementation. The implementation returned by this method depends on the type of ViewResolver being used, for example, InternalResourceViewResolver or FreeMarkerViewResolver.

2. ‘setViewNames(String... viewNames)‘ - This method is used to set the list of view names supported by the view resolver.

The ViewResolver can be configured in the Spring application context through either Java configuration or XML configuration. Spring provides several built-in ViewResolver implementations, such as InternalResourceViewResolver, which resolves JSP views, and FreeMarkerViewResolver, which resolves FreeMarker templates.

Here is an example of how to configure ViewResolver in Spring MVC using Java configuration:

@Configuration
@EnableWebMvc
public class AppConfig implements WebMvcConfigurer {
 
    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
 
    // Other configuration methods...
}

In this example, the InternalResourceViewResolver is used to resolve JSP views. The ‘prefix‘ property indicates the path to the JSP files, and the ‘suffix‘ property indicates the file extension. So, when the controller returns the view name "example", the InternalResourceViewResolver will search for a JSP file with the path "/WEB-INF/views/example.jsp".

In summary, the ViewResolver plays a crucial role in the Spring MVC framework as it connects the controller and the view and determines the actual view implementation based on the view name.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Spring Framework interview — then scores it.
📞 Practice Spring Framework — free 15 min
📕 Buy this interview preparation book: 100 Spring Framework questions & answers — PDF + EPUB for $5

All 100 Spring Framework questions · All topics