org.springframework.web.servlet package
. It dispatches the request to the appropriate controller and manages the flow of the application. It is required to specify the DispatcherServlet class in the web.xml
file. xml
file or properties
file. In this file, we generally define the base-package and view resolver where DispatcherServlet
searches for the controller classes and view components path. However, it can also contain various other configuration properties. InternalResourceViewResolver
is a class which is used to resolve internal view in Spring MVC. Here, you can define the properties like prefix and suffix where prefix contains the location of view page and suffix contains the extension of view page.<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
ModelMap
has a similar purpose, with the ability to pass a collection of values. It then treats those values as if they were within a Map. We should note that in Model (ModelMap
) we can only store data. We put data in and return a view name.ModelAndView
, we return the object itself. We set all the required information, like the data and the view name, in the object we're returning.JSR-303
Annotations and any reference implementation, for example, Hibernate Validator.org.springframework.validation
.Validator interface.@Controller
annotation is used to declare a class as a controller class. It is required to specify this annotation on the class name. For example :@Controller
class Demo
{
}
@RequestMapping
annotation is used to map the controller class and its methods. You can specify this annotation on the class name as well as method name with a particular URL that represents the path of the requested page. For example :@Controller
@RequestMapping("/ form")
class Demo
{
@RequestMapping("/show")
public String display()
{
}
}
<servlet>
<servlet-name>Spring</servlet-name>
<servlet-class>
org.Springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
@PathVariable
is an annotation that is used as a parameter in the handler method for extracting the value of the URI template.@RequestMapping("/Login/{Lid}")
public String handleRequest(@PathVariable("Lid") String Login, Model map)
{
}
@RequestBody
annotation is responsible for binding the HTTP body
request to a domain object. The incoming HTTP request
is automatically de-serialized to the Java object by Spring with the help of the HTTP message
converters. @ResponseBody
annotation is used in the MVC controller, it indicates that the developer needs to write a return type of declared method directly to the HTTP response body
. Here, invoking of the model is not required and the view name is not interpreted by Spring. web.xml
using the parameter :<servlet>
<servlet-name>Spring</servlet-name>
<servlet-class>
org.Springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
WEB-INF/Spring-dao-hibernate.xml,
</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>
<beans>
<import resource="Spring-dao-hibernate.xml"/>
</beans>
ContextLoaderListener
is a listener that helps to bootstrap Spring MVC. As the name suggests, it loads and creates the ApplicationContext
, so you don't have to write explicit code to do create it.WebAppliationContext
.ContextLoaderListener
also ties the lifecycle of the ApplicationContext
to the lifecycle of the ServletContext
. You can get the ServletContext
from the WebApplicationContext
using the getServletContext()
method.@RequestParam
is a Spring MVC annotation that is used to extract a request parameter or query parameters from the URL in the Controller's handler method as shown below : public String personDetail(@RequestParam("id") long id){
....
return "personDetails";
}
@RequestParam
annotation also supports data type conversion, e.g. you can see here a String is converted to log automatically, but it can also result in an exception if query parameter is not present or in case of type mismatch. You can also make the parameter optional by using requried=false
, e.g. @RequestParam (value="id", required=false )
@ExceptionHandler
Annotation : ExceptionHandler is a Spring annotation handle exceptions thrown by request handling. This annotation works at the @Controller
level.<em><strong>@ControllerAdvice</strong></em>
Annotation : This annotation supports global Exception handler mechanism. A controller advice allows you to use exactly the same exception handling techniques but applies them across the application, not just to an individual controller.HandlerExceptionResolver
: Resolve any exception thrown by the application.LocalResolver
to handle internationalization and localization. To enable support for the localization in your application, we need to register below two beans.SessionLocaleResolver
: LocaleResolver implementation that uses a locale attribute in the user’s session in case of a custom setting, with a fallback to the specified default locale or the request’s accept-header locale.LocaleChangeInterceptor
: Interceptor that allows for changing the current locale on every request, via a configurable request parameter (default parameter name: “locale”
).@Bean
public LocaleResolver localeResolver(){
SessionLocaleResolver localeResolver = new SessionLocaleResolver();
localeResolver.setDefaultLocale(Locale.US);
return localeResolver;
}
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("language");
return localeChangeInterceptor;
}
@EnableWebMvc
annotation allows you to configure Spring application without using the XML
based configuration/declaration. This annotation is equivalent to using the <mvc:annotation-driven />
in XML
. Here is the list of some important features of the @EnableWebMvc
annotation :JSR-303
bean validation.HttpMessageConverter
support.HttpServletRequest
interface : The HttpServletRequest is a java interface present in javax.servlet.http
package. Like Servlets, you can use HttpServletRequest
in Spring to read the HTML form data provided by the user.@RequestParam
annotation : The @RequestParam
annotation reads the form data and binds it automatically to the parameter present in the provided method.@ModelAttribute
annotation : The @ModelAttribute
annotation binds a method parameter or its return value to a named model attribute.JSR-303/309
implementation that allows to express and validate application constraints.@Min
annotation : It is required to pass an integer value with @Min
annotation. The user input must be equal to or greater than this value.@Max
annotation : It is required to pass an integer value with @Max
annotation. The user input must be equal to or smaller than this value.Reusability :
We can reuse a single component in multiple pages like header and footer components.Centralized control :
We can control the layout of the page by a single template page only.Easy to change the layout :
By the help of a single template page, we can change the layout of the page anytime. So your website can easily adopt new technologies such as bootstrap and jQuery.PreparedStatementCreator
is one of the most commonly used interfaces for writing data to the database. createPreparedStateme
nt() is a method that can be used to create and return PreparedStatement from the Connection argument, and exception handling is automatically taken care of. When this interface is implemented, a different interface SqlProvider
can also be implemented which has a method called getSql()
. This method is useful for providing sql strings to the JdbcTemplate. It does not handle SQLExceptions
. InternalResourceViewResolver
bean in spring XML
where we need to define prefix and suffix of the views name.<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
HandlerInterceptor
interface forces to implement all the three methods preHandle()
, postHandle()
and afterCompletion()
irrespective of whether it is needed or not. To avoid that, you can use HandlerInterceptorAdapter
class that implements HandlerInterceptor and provides default empty implementations. Extending HandlerInterceptorAdapter
class allows you to override only the method that are required.