Spring MVC Questions and Answers
Spring MVC Questions and Answers
Spring MVC Questions and Answers
What is DispatcherServlet?
DispatcherServlet is the front controller of Spring MVC.IT has to be configured in web.xml file.
<web-app>
<display-name>Application Name</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 1/12 |
This page was exported from - TechnicalStack
Export date: Sat May 18 14:08:48 2019 / +0000 GMT
What is SimpleUrlHandlerMapping?
SimpleUrlHandlerMapping is one of the implementation of Handler Mapping interface. It is most commonly used handler mapping.
In this, we have to configure the incoming request to handler by bean id or name in the configuration file.
We have to set the mapping property of the SimpleUrlHandlerMapping with key as the request and value as the handler
The request ?<url>/saveEmployee.htm' will be handled by SaveEmployeeController and
?<url/deleteEmployee.htm>' will be handled by deleteEmployeeController.
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/saveEmployee.htm">saveEmployeeController</prop>
<prop key="/deleteEmployee.htm">deleteEmployeeController</prop>
</props>
</property>
</bean>
<bean id="saveEmployeeController" class="com.answersz.employee.SaveEmployeeController" />
<bean id="deleteEmployeeController" class="com.answersz.employee.DeleteEmployeeController" />
- BeanNameUrlHandlerMapping
- SimpleUrlHandlerMapping
- ControllerClassNameHandlerMapping
- CommonsPathMapHandlerMapping
- DefaultAnnotationHandlerMapping
- RequestMappingHandlerMapping
What is ControllerClassNameHandlerMapping?
ControllerClassNameHandlerMapping is one of the implementation of Handler Mapping interface. In this mapping, the name of the
controller itself acts as the request. The following are the conventions need to following
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 2/12 |
This page was exported from - TechnicalStack
Export date: Sat May 18 14:08:48 2019 / +0000 GMT
- UrlBasesViewResolver
- InternalResourceViewResolver
- ResourceBundleViewResolver
- BeanNameViewResolver
- XmlViewResolver
What are the different built in Controller implementations available in Spring Web
MVC?
Following are built in Controller implementations available in Spring Web MVC
- Controller
- AbstractCommandController
- SimpleFormController
- WizardFormController
- MultiActionController
What is InternalResourceViewResolver ?
What is ResourceBundleViewResolver ?
What is XmlViewResolver?
Give examples of important Spring MVC annotations?
Important Spring MVC annotations are listed below.
@Controller : This class would serve as a controller.
@RequestMapping : Can be used on a class or a method. Maps an url on the class (or method).
@PathVariable : Used to map a dynamic value in the url to a method argument.
Example 1 : Maps a url ?/players ? for the controller method.
@RequestMapping(value="/players", method=RequestMethod.GET)
public String findAllPlayers(Model model) {
Example 2 : If a url /players/15 is keyed in, playerId is populated with value 15.
@RequestMapping(value="/players/{playerid}", method=RequestMethod.GET)
public String findPlayer(@PathVariable String playerId, Model model) {
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 3/12 |
This page was exported from - TechnicalStack
Export date: Sat May 18 14:08:48 2019 / +0000 GMT
How can we use Spring to create Restful Web Service returning JSON response?
For adding JSON support to your spring application, you will need to add Jackson dependency in first step.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 4/12 |
This page was exported from - TechnicalStack
Export date: Sat May 18 14:08:48 2019 / +0000 GMT
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 5/12 |
This page was exported from - TechnicalStack
Export date: Sat May 18 14:08:48 2019 / +0000 GMT
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
b) OR, you can import them into existing configuration file you have already configured.
<beans>
<import resource="spring-dao-hibernate.xml"/>
<import resource="spring-services.xml"/>
<import resource="spring-security.xml"/>
... //Other configuration stuff
</beans>
Difference between <context:annotation-config> vs <context:component-scan>?
1) First big difference between both tags is that <context:annotation-config> is used to activate applied annotations in already
registered beans in application context. Note that it simply does not matter whether bean was registered by which mechanism e.g.
using <context:component-scan> or it was defined in application-context.xml file itself.
2) Second difference is driven from first difference itself. It registers the beans defined in config file into context + it also scans the
annotations inside beans and activate them. So <context:component-scan> does what <context:annotation-config> does, but
additionally it scan the packages and register the beans in application context.
<context:annotation-config> = Scanning and activating annotations in ?already registered beans?.
<context:component-scan> = Bean Registration + Scanning and activating annotations
ViewResolver is an interface to be implemented by objects that can resolve views by name. There are plenty of ways using which
you can resolve view names. These ways are supported by various in-built implementations of this interface. Most commonly used
implementation is InternalResourceViewResolver class. It defines prefix and suffix properties to resolve the view component.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 6/12 |
This page was exported from - TechnicalStack
Export date: Sat May 18 14:08:48 2019 / +0000 GMT
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
So with above view resolver configuration, if controller method return ?login? string, then the ?/WEB-INF/views/login.jsp? file will
be searched and rendered.
What is a MultipartResolver and when its used?
Spring comes with MultipartResolver to handle file upload in web application. There are two concrete implementations included in
Spring:
If a DispatcherServlet detects a multipart request, it will resolve it via the configured MultipartResolver and pass on a wrapped
HttpServletRequest. Controllers can then cast their given request to the MultipartHttpServletRequest interface, which permits access
to any MultipartFiles.
How to upload file in Spring MVC Application?
Let's say we are going to use CommonsMultipartResolver which uses the Apache commons upload library to handle the file upload
in a form. So you will need to add the commons-fileupload.jar and commons-io.jar dependencies.
import org.springframework.web.multipart.MultipartFile;
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 7/12 |
This page was exported from - TechnicalStack
Export date: Sat May 18 14:08:48 2019 / +0000 GMT
{
private MultipartFile file;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import com.technicalstack.form.FileUploadForm;
@Controller
public class FileUploadController
{
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String save(@ModelAttribute("uploadForm") FileUploadForm uploadForm, Model map) {
if (multipartFile != null) {
fileName = multipartFile.getOriginalFilename();
}
map.addAttribute("files", fileName);
return "file_upload_success";
}
}
The upload JSP file looks like this:
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 8/12 |
This page was exported from - TechnicalStack
Export date: Sat May 18 14:08:48 2019 / +0000 GMT
Using JSR-303 Annotations and any reference implementation e.g. Hibernate Validator
Using custom implementation of org.springframework.validation.Validator interface
In next question, you see an example about how to use validation support in spring MVC application.
How to validate form data in Spring Web MVC Framework?
Spring MVC supports validation by means of a validator object that implements the Validator interface. You need to create a class
and implement Validator interface. In this custom validator class, you use utility methods such as rejectIfEmptyOrWhitespace() and
rejectIfEmpty() in the ValidationUtils class to validate the required form fields.
@Component
public class EmployeeValidator implements Validator
{
public boolean supports(Class clazz) {
return EmployeeVO.class.isAssignableFrom(clazz);
}
To activate this custom validator as a spring managed bean, you need to do one of following things:
1) Add @Component annotation to EmployeeValidator class and activate annotation scanning on the package containing such
declarations.
As you know about servlet filters that they can pre-handle and post-handle every web request they serve ? before and after it's
handled by that servlet. In the similar way, you can use HandlerInterceptor interface in your spring mvc application to pre-handle
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 9/12 |
This page was exported from - TechnicalStack
Export date: Sat May 18 14:08:48 2019 / +0000 GMT
and post-handle web requests that are handled by Spring MVC controllers. These handlers are mostly used to manipulate the model
attributes returned/submitted they are passed to the views/controllers.
A handler interceptor can be registered for particular URL mappings, so it only intercepts requests mapped to certain URLs. Each
handler interceptor must implement the HandlerInterceptor interface, which contains three callback methods for you to implement:
preHandle(), postHandle() and afterCompletion().
Problem with HandlerInterceptor interface is that your new class will have to implement all three methods irrespective of whether it
is needed or not. To avoid overriding, you can use HandlerInterceptorAdapter class. This class implements HandlerInterceptor and
provide default blank implementations.
In a Spring MVC application, you can register one or more exception resolver beans in the web application context to resolve
uncaught exceptions. These beans have to implement the HandlerExceptionResolver interface for DispatcherServlet to auto-detect
them. Spring MVC comes with a simple exception resolver for you to map each category of exceptions to a view i.e.
SimpleMappingExceptionResolver to map each category of exceptions to a view in a configurable way.
Let's say we have an exception class i.e. AuthException. And we want that everytime this exception is thrown from anywhere into
application, we want to show a pre-determined view page /WEB-INF/views/error/authExceptionView.jsp. So the configuration
would be.
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.technicalstack.demo.exception.AuthException">
error/authExceptionView
</prop>
</props>
</property>
<property name="defaultErrorView" value="error/genericView"/>
</bean>
The ?defaultErrorView? property can be configured to show a generic message for all other exceptions which are not configured
inside ?exceptionMappings? list.
Spring framework is shipped with LocaleResolver to support the internationalization and thus localization as well. To make Spring
MVC application supports the internationalization, you will need to register two beans.
1) SessionLocaleResolver : It resolves locales by inspecting a predefined attribute in a user's session. If the session attribute doesn't
exist, this locale resolver determines the default locale from the accept-language HTTP header.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 10/12 |
This page was exported from - TechnicalStack
Export date: Sat May 18 14:08:48 2019 / +0000 GMT
2) LocaleChangeInterceptor : This interceptor detects if a special parameter is present in the current HTTP request. The parameter
name can be customized with the paramName property of this interceptor. If such a parameter is present in the current request, this
interceptor changes the user's locale according to the parameter value.
Simply implement ServletContextAware and ServletConfigAware interfaces and override below methods.
@Controller
@RequestMapping(value = "/magic")
public class SimpleController implements ServletContextAware, ServletConfigAware {
@Override
public void setServletConfig(final ServletConfig servletConfig) {
this.config = servletConfig;
@Override
public void setServletContext(final ServletContext servletContext) {
this.context = servletContext;
}
//other code
}
For using servlet container configured JNDI DataSource, we need to configure it in the spring bean configuration file and then inject
it to spring beans as dependencies. Then we can use it with JdbcTemplate to perform database operations.
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 11/12 |
This page was exported from - TechnicalStack
Export date: Sat May 18 14:08:48 2019 / +0000 GMT
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com | Page 12/12 |