Home  >  Spring Interview Q & A

Interview Questions: Spring MVC

March 19, 2015

Qns-1: What is the role of DispatcherServlet in Spring MVC?

Ans: DispatcherServlet is the servlet by which Spring handles HTTP request and redirects the request to required resources. To work with Spring MVC, we need to define it in our web.xml .
<servlet>
   <servlet-name>dispatcher</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   <load-on-startup>1</load-on-startup>
</servlet> 

Qns-2: What is minimum web.xml configuration to run Spring MVC?

Ans: To run the Spring MVC, we need to define DispatcherServlet, contextConfigLocation and ContextLoaderListener in web.xml. Find the sample web.xml.
<servlet>
	<servlet-name>dispatcher</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
	<servlet-name>dispatcher</servlet-name>
	<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> 




Qns-3: How to handle views in Spring MVC using XML?

Ans: To handle views in Spring MVC, we need to configure InternalResourceViewResolver bean in spring XML where we need to define prefix and suffix of our views name. Find the sample declaration.
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/pages/"/>
  <property name="suffix" value=".jsp"/> 
</bean> 

Qns-4: How to start Spring MVC using spring boot?

Ans: Spring provides spring-boot-starter-web using which we can resolve all Spring MVC required JAR. In our project, we can include it using maven as
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
        <version>1.2.2.RELEASE</version>	
</dependency> 
If we want to use gradle, we use as
dependencies {
   compile 'org.springframework.boot:spring-boot-starter-web:1.2.2.RELEASE'
} 

Qns-5: How to create Controller class in Spring MVC?

Ans: To create a Controller in Spring MVC, create a class and annotate it with @Controller and @RequestMapping. @Controller declares this to be controller and @RequestMapping defines the path mapping of controller. Find the sample controller.
@Controller
@RequestMapping("/page")
public class PersonController {
	@Autowired
	private IPersonService personService;
	@RequestMapping("/login")
        public String hello(@RequestParam(value="userId", required=false) String userId,
    		@RequestParam(value="location", required=false) String location,
    		Model model) {
	        model.addAttribute("msg", "Hello "+personService.getPersonName() );
	        model.addAttribute("userId", userId);
	        model.addAttribute("location", location);
                return "result";
	}
} 

We need to create method annotated with @RequestMapping. Using this mapping request, URL finds the method to execute. @RequestParam annotation is used to get request parameter. Model class is used to respond values. Using Model. addAttribute(key,value) , we send the values to respond back. The URL will become /page/login to execute hello() method in the above controller code snippet. The return value of the method is view name. In the above case, result.jsp will be executed.

Qns-6: How to access values from Model in JSP.

Ans: Use JSTL, to retrieve values from Model as
${userId}
${location} 

Qns-7: How to configure DispatcherServlet without web.xml in Spring MVC?

Ans: Create a class implementing WebApplicationInitializer interface. We need to define onStartup() method. Here we can register annotation based application configuration class, servlet and mappings, listener etc. Find the sample WebApplicationInitializer.
public class WebAppInitializer implements WebApplicationInitializer {
   public void onStartup(ServletContext servletContext) throws ServletException {  
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();  
        ctx.register(AppConfig.class);  
        ctx.setServletContext(servletContext);    
        Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));  
        dynamic.addMapping("/");  
        dynamic.setLoadOnStartup(1);  
   }  
} 

In ServletContext instance, we add servlet. Using javax.servlet.ServletRegistration.Dynamic class we define mappings for the servlet.

Qns-8: How to define Spring MVC view in @Configuration class without spring XML.

Ans: We need to create a bean in @Configuration class for UrlBasedViewResolver. This class has different methods like setPrefix, setSuffix and setViewClass. Find the sample bean definition for UrlBasedViewResolver.
@Bean  
public UrlBasedViewResolver setupViewResolver() {  
	UrlBasedViewResolver resolver = new UrlBasedViewResolver();  
	resolver.setPrefix("/views/");  
	resolver.setSuffix(".jsp");  
	resolver.setViewClass(JstlView.class);
	return resolver;  
} 

Qns- 9: How to handle Multipart to upload file in Spring MVC?

Ans: First we need to define a bean MultipartConfigElement in our configuration class. Here we can define maximum file size and other configuration related to file upload. We do it as
@Bean
public MultipartConfigElement multipartConfigElement() {
     MultipartConfigFactory factory = new MultipartConfigFactory();
     factory.setMaxFileSize("128KB");
     factory.setMaxRequestSize("128KB");
     return factory.createMultipartConfig();
} 

In WebApplicationInitializer implementation we need to register MultipartConfigElement as
Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));  
dynamic.setMultipartConfig(ctx.getBean(MultipartConfigElement.class)); 

Now in controller class, the methods must be defined with the<> MultipartFile argument as
@RequestMapping(value="/singleSave", method=RequestMethod.POST )
    public @ResponseBody String singleSave(@RequestParam("file") MultipartFile file,
	@RequestParam("desc") String desc ){
} 

Qns-10: What is the role of @EnableWebMvc in Spring MVC.

Ans: @EnableWebMvc annotation is applied on configuration class with @Configuration annotation. Using @EnableWebMvc, spring enables the MVC related configuration.
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us