Spring MVC

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 46

Spring MVC

February 2019
Version 1.0
CitiusTech has prepared the content contained in this document based on information and knowledge that it reasonably believes to be
reliable. Any recipient may rely on the contents of this document at its own risk and CitiusTech shall not be responsible for any error
and/or omission in the preparation of this document. The use of any third party reference should not be regarded as an indication of
an endorsement, an affiliation or the existence of any other kind of relationship between CitiusTech and such third party
Agenda

▪ Introduction to Spring MVC


▪ Components of Spring MVC
▪ Setting up Spring MVC application
▪ Spring MVC Annotations
▪ References

2
Introduction to Spring MVC
Based on the Model-View-Controller (MVC) pattern, Spring MVC helps you build web-based
applications that are as flexible and as loosely coupled as the Spring Framework itself.

3
Components of Spring MVC (1/6)
The below figure explains the flow and components of a typical spring web application

4
Components of Spring MVC (2/6)
DispatcherServlet
▪ In the case of Spring MVC, DispatcherServlet is the front controller
▪ A front controller is a common web application pattern where a single servlet delegates
responsibility for a request to other components of an application to perform actual processing
▪ The DispatcherServlet’s job is to send the request on to a Spring MVC controller

5
Components of Spring MVC (3/6)
Controller
▪ A controller is a Spring component that processes the request
▪ A controller acts a servlet in Spring MVC

6
Components of Spring MVC (4/6)
Handler Mapping
▪ A typical application may have several controllers and DispatcherServlet needs some help
deciding which controller to send the request
▪ So the DispatcherServlet consults one or more handler mappings to figure out where the
request’s next stop will be
▪ The handler mapping will pay particular attention to the URL carried by the request when making
its decision

7
Components of Spring MVC (5/6)
Model and logical view name (ModelandView):
▪ The logic performed by a controller often results in some information that needs to be carried
back to the user and displayed in the browser
▪ This information is referred to as the model
▪ But sending raw information back to the user isn’t sufficient—it needs to be formatted in a user-
friendly format, typically HTML. For that the information needs to be given to a view, typically a
JSP
▪ One of the last things that a controller does is package up the model data and identify the name
of a view that should render the output
▪ It then sends the request, along with the model and view name, back to the DispatcherServlet
▪ So that the controller doesn’t get coupled to a particular view, the view name passed back to
DispatcherServlet doesn’t directly identify a specific JSP. In fact, it doesn’t even necessarily
suggest that the view is a JSP at all. Instead, it only carries a logical name which will be used to
look up the actual view that will produce the result

8
Components of Spring MVC (6/6)
ViewResolver
▪ The DispatcherServlet will consult a view resolver to map the logical view name to a specific view
implementation, which may or may not be a JSP
▪ Now that DispatcherServlet knows which view will render the result, the request’s job is almost
over. Its final stop is at the view implementation (probably a JSP) where it delivers the model data

9
Agenda

▪ Introduction to Spring MVC


▪ Components of Spring MVC
▪ Setting up Spring MVC application
▪ Spring MVC Annotations
▪ References

10
Setting up Spring MVC (1/13)
▪ Let us now understand steps involved in setting up Spring MVC with help of a simple example
which will render home page when user hits the URL http://localhost:8080/home

11
Setting up Spring MVC (2/13)
Step 1: To Set up DispatcherServlet
▪ DispatcherServlet is at the heart of Spring MVC that functions as Spring MVC’s front controller.
Like any other servlet, DispatcherServlet needs to be configured in web application’s web.xml file
something like this:
<!-- Configuring DispatcherServlet. -->
<servlet>
<servlet-name>demo</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet- class>
</servlet>

<servlet-mapping>
<servlet-name>demo</servlet-name>
<url-pattern>/home</url-pattern>
</servlet-mapping>

12
Setting up Spring MVC (3/13)
Step 2: Writing a basic controller:
▪ Below is the code for the basic controller which sends a ModelAndView as a response to client
@Controller
public class BasicController {
public ModelAndView showHomePage(HttpServletRequest request,
HttpServletResponse response) throws Exception {
//Return view with logical name as home.
return new ModelAndView("home");
}
}

13
Setting up Spring MVC (4/13)
Step 3: Declaring handler mapping
▪ DispatcherServlet consults one or more handler mappings in order to know which controller to
dispatch a request to
▪ Types of handler mappings supported by Spring MVC are:
• BeanNameUrlHandlerMapping
• ControllerBeanNameHandlerMapping
• ControllerClassNameHandlerMapping
• SimpleUrlHandlerMapping
• DefaultAnnotationHandlerMaping
▪ Using one of the handler beans is usually just a matter of configuring it as a bean in Spring. if no
handler mapping beans are found, then DispatcherServlet creates and uses
BeanNameUrlHandlerMapping and DefaultAnnotationHandler- Mapping

14
Setting up Spring MVC (5/13)
Types of handler mappings
▪ BeanNameUrlHandlerMapping– Maps controllers to URLs that are based on controller’s name
▪ ControllerBeanNameHandlerMapping – Similar to BeanNameUrlHandlerMapping maps
controllers to URLs that are based on controller bean’s name. In this case, the bean names aren’t
required to follow the URL conventions
▪ ControllerClassNameHandlerMapping— Maps controllers to URLs by using the controllers’ class
names as the basis for their URLs
▪ SimpleUrlHandlerMapping – Maps controllers to the URLs using property collection defined in
the Spring’s application conext
▪ DefaultAnnotationHandlerMaping – Maps requests to the controllers and controller methods
that are annotated with @RequestMapping

15
Setting up Spring MVC (6/13)
▪ An example of “SimpleUrlHandlerMapping “
<!-- Declaring the controller bean. -->
<bean id = "basicController" class = "com.citius.training.demo.controller.BasicController" />

<!-- Creating handler mapping -->


<bean id = "simpleUrlHandlerMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap">
<map>
<entry key="/demo" value="basicController"></entry>
</map>
</property>
</bean>

16
Setting up Spring MVC (7/13)
Step 4: Resolving views:
▪ The last thing of course is rendering output to the user. This job falls to some view
implementation—typically Java Server Pages (JSP), but other view technologies such as Velocity
or FreeMarker may be used
▪ In order to figure out which view should handle a given request, DispatcherServlet consults a
view resolver to exchange the logical view name returned by a controller for an actual view that
should render the results
▪ In reality, a view resolver’s job is to map a logical view name to some implementation of
org.springframework.web.servlet.View
▪ Similar to handler mapping, view resolver needs to be configured as a bean in Spring MVC’s
application context

17
Setting up Spring MVC : Types of View resolvers (8/13)
View Resolver Description
BeanNameViewResolver Finds an implementation of View that’s registered as a
<bean> whose ID is the same as the logical view name.
ContentNegotiatingViewResolver Delegates to one or more other view resolvers, the choice
of which is based on the content type being requested.
FreeMarkerViewResolver Finds a FreeMarker-based template whose path is deter-
mined by prefixing and suffixing the logical view name.
InternalResourceViewResolver Finds a view template contained within the web applica-
tion’s WAR file. The path to the view template is derived by
prefixing and suffixing the logical view name.
JasperReportsViewResolver Finds a view defined as a Jasper Reports report file whose
path is derived by prefixing and suffixing the logical view
name.
ResourceBundleViewResolver Looks up View implementations from a properties file.

18
Setting up Spring MVC : Types of View resolvers (9/13)
View Resolver Description
TilesViewResolver Looks up a view that is defined as a Tiles template. The name of
the template is the same as the logical view name.
UrlBasedViewResolver This is the base class for some of the other view resolv- ers, such
as InternalResourceViewResolver. It can be used on its own, but
it’s not as powerful as its sub- classes. For example,
UrlBasedViewResolver is unable to resolve views based on the
current locale.
VelocityLayoutViewResolver This is a subclass of VelocityViewResolver that sup- ports page
composition via Spring’s VelocityLayout- View (a view
implementation that emulates Velocity’s VelocityLayoutServlet).
XmlViewResolver Finds an implementation of View that’s declared as a <bean> in an
XML file (/WEB-INF/views.xml).

19
Setting up Spring MVC (10/13)
InternalResourceViewResolver Example
▪ Below piece of code shows how to configure InternalResourceViewResolver as a view resolver
<!-- Setting up the view resolver -->
<bean id = "internalResourceViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>

20
Setting up Spring MVC (11/13)
Step 5: Creating the application context for spring MVC:
▪ The DispatcherServlet loads the application context from the xml file whose name is based on
the <servlet-name> tag in web.xml
▪ For e.g.
<servlet>
<servlet-name>demo</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherServlet</servlet
- class>
</servlet>
▪ The above servlet definition will load the application context from file named demo-servlet.xml
located in the WEB-INF folder of the web application

21
Setting up Spring MVC (12/13)
An Example of Spring MVC application context XML configuration
▪ Below code snippet shows a basic application context for Spring MVC:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<!-- Declaring the controller bean. -->
<bean id = "basicController" class = "com.citius.training.demo.controller.BasicController" />

22
Setting up Spring MVC (13/13)
An Example of Spring MVC application context XML configuration continued
<!-- Creating handler mapping -->
<bean id = "simpleUrlHandlerMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap">
<map>
<entry key="/demo" value="basicController"></entry>
</map>
</property>
</bean>
<!-- Setting up the view resolver -->
<bean id = "internalResourceViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>

23
Agenda

▪ Introduction to Spring MVC


▪ Components of Spring MVC
▪ Setting up Spring MVC application
▪ Spring MVC Annotations
▪ References

24
Spring MVC Annotations
Spring version 3.0 introduced support for annotations into its MVC module which reduce the amount
of configuration that needs to be done in application context.
Below are the Spring MVC annotations:
▪ @Controller
▪ @RequestMapping
▪ @ModelAttribute
▪ @RequestBody
▪ @ResponseBody
▪ @RequestParam
▪ @PathVariable
▪ @RequestHeader
▪ @CookieValue
▪ @InitBinder

25
Spring MVC Annotations : Controller (1/2)
▪ The @Controller annotation indicates that a particular class serves the role of a controller. If you
annotate your class as a Controller then you need not extend any of the base controller classes or
reference the Servlet API
▪ The dispatcher scans such annotated classes for mapped methods and detects @RequestMapping
annotations (discussed next)
▪ You can define annotated controller beans explicitly, using a standard Spring bean definition in the
dispatcher's context. However, the @Controller stereotype also allows for autodetection, aligned
with Spring general support for detecting component classes in the classpath and auto-registering
bean definitions for them

26
Spring MVC Annotations : Controller (2/2)
▪ To enable autodetection of such annotated controllers, you add component scanning to your
configuration. Use the spring-context schema as shown in the following XML snippet:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.citius.training.demo" />
</beans>

27
Spring MVC Annotations : RequestMapping (1/2)
▪ @RequestMapping can be used at a class level or at method level. The @RequestMapping
annotation maps URLs such as /home onto an entire class or a particular handler method.
Typically the class-level annotation maps a specific request path (or path pattern) onto a form
controller, with additional method-level annotations narrowing the primary mapping for a
specific HTTP method request method ("GET", "POST", etc.) or an HTTP request parameter
condition. The below code shows an example of @RequestMapping annotation
@RequestMapping(value = {"/patientLabs.xml","/patientLabs.json"}, method =
{RequestMethod.POST, RequestMethod.PUT},
produces = {"application/json", "application/xml"},
consumes ={"application/json", "application/xml"})
public PersistResponse persistPatientData(@RequestBody PatientLabObject
patientLabObject,
HttpServletRequest request, HttpServletResponse response){
//Code Goes Here.

28
Spring MVC Annotations : RequestMapping (2/2)
Attributes are :-
▪ value: indicates the URL that the method serves
▪ method: indicates the HTTP Methods (GET/POST/PUT) that the controller supports
▪ consumes: attribute indicates the media types that a particular controller accepts
▪ produces: attribute indicates the media type of the response that the controller method will
produce
▪ params: You can narrow request matching through request parameter conditions such as
"myParam", "!myParam", or "myParam=myValue". The first two test for request parameter
presence/absence and the third for a specific parameter value
▪ headers: Same as params the headers attributes applies for request headers

29
Spring MVC Annotations : ModelAttribute (1/2)
▪ @ModelAttribute on a method argument indicates the argument should be retrieved from the
model
▪ If not present in the model, the argument should be instantiated first and then added to the
model
▪ Once present in the model, the argument's fields should be populated from all request
parameters that have matching names. This is known as data binding in Spring MVC, a very useful
mechanism that saves you from having to parse each form field individually
@RequestMapping(value = "/saveContacts", method = RequestMethod.POST)
public ModelAndView saveContacts(@Valid @ModelAttribute
ContactDetails
contactDetails, BindingResult bindingResult){
}

30
Spring MVC Annotations : ModelAttribute (2/2)
Given the example in the previous slide, where can the ContactDetails instance come from? There
are several options:
▪ It may already be in the model due to use of @SessionAttributes to store model attributes in the
HTTP session between requests
▪ It may already be in the model due to an @ModelAttribute method in the same controller as
shown below:
@RequestMapping(value = "/", method = RequestMethod.GET)
public String showHomePage(Model model){
if(model.asMap().get("contactDetails") == null){
model.addAttribute(new ContactDetails());
}

return "/contacts";
}

The above method displays the home page for Contact Management application and adds the
contactDetails object into model

31
Spring MVC Annotations : RequestBody (1/3)
▪ The @RequestBody method parameter annotation indicates that a method parameter should be
bound to the value of the HTTP request body
public PersistResponse persistPatientData(@RequestBody
PatientLabObject
patientLabObject,
HttpServletRequest request, HttpServletResponse response){
//Code
}
▪ The above code indicates that the patientLabObject must be bound to the request body. Thus
there must be some mechanism to convert the request body to PatientLabObject type
▪ You convert the request body to the method argument by using an HttpMessageConverter

32
Spring MVC Annotations : RequestBody (2/3)
▪ HttpMessageConverter is responsible for converting from the HTTP request message to an object
and converting from an object to the HTTP response body. The RequestMappingHandlerAdapter
supports the @RequestBody annotation with the following default HttpMessageConverters:
• ByteArrayHttpMessageConverter converts byte arrays
• StringHttpMessageConverter converts strings
• FormHttpMessageConverter converts form data to/from a MultiValueMap<String, String>
• SourceHttpMessageConverter converts to/from a javax.xml.transform.Source
▪ If you intend to read and write XML, you will need to configure the
MarshallingHttpMessageConverter with a specific Marshaller and an Unmarshaller
implementation from the org.springframework.oxm package. The example below shows how to
do that directly in your configuration

33
Spring MVC Annotations : RequestBody (3/3)
▪ Configuration to convert JSON/XML sent in HTTP request body to java object
<bean id = "requestMappingHandlerAdapter“
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" />
</list>
</property>
</bean>

34
Spring MVC Annotations : ResponseBody
▪ The @ResponseBody annotation is similar to @RequestBody. This annotation can be put on a
method and indicates that the return type should be written straight to the HTTP response body
(and not placed in a Model, or interpreted as a view name)
▪ For example
@RequestMapping(value = {"/patientLabs.xml","/patientLabs.json"}, method =
{RequestMethod.POST, RequestMethod.PUT},
produces = {"application/json", "application/xml"},
consumes ={"application/json", "application/xml"})
@ResponseBody
public PersistResponse persistPatientData(@RequestBody PatientLabObject
patientLabObject,
HttpServletRequest request, HttpServletResponse response){
//Code
}
▪ As with @RequestBody, Spring converts the returned object to a response body by using an
HttpMessageConverter

35
Spring MVC Annotations : RequestParam
▪ Use the @RequestParam annotation to bind request parameters to a method parameter in your
controller
▪ For example:
@RequestMapping(value = {"/patientLabDetails.xml","/patientLabDetails.json"},
produces = {"application/json", "application/xml"})
public FetchResponse getPatientLabDetails(@RequestParam String patientId,
HttpServletResponse response){
//Code
}
▪ Parameters using this annotation are required by default, but you can specify that a parameter is
optional by setting @RequestParam's required attribute to false (e.g.,
@RequestParam(value="id", required=false))
▪ Type conversion is applied automatically if the target method parameter type is not String

36
Spring MVC Annotations : PathVariable (1/2)
▪ In Spring MVC you can use the @PathVariable annotation on a method argument to bind it to the
value of a URI template variable:
@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable String ownerId, Model model) {
Owner owner = ownerService.findOwner(ownerId);
model.addAttribute("owner", owner);
return "displayOwner";
}

▪ The URI Template "/owners/{ownerId}" specifies the variable name ownerId. When the controller
handles this request, the value of ownerId is set to the value found in the appropriate part of the
URI. For example, when a request comes in for /owners/fred, the value of ownerId is fred

37
Spring MVC Annotations : PathVariable (2/2)
▪ To process the @PathVariable annotation, Spring MVC needs to find the matching URI template
variable by name. You can specify it in the annotation:
@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable("ownerId") String theOwner, Model model) {
// implementation omitted
}

38
Spring MVC Annotations : RequestHeader
▪ The @RequestHeader annotation allows a method parameter to be bound to a request header
▪ Here is a sample request header:
Host localhost:8080
Accept text/html,application/xhtml+xml,application/xml;q=0.9
Accept-Language fr,en-gb;q=0.7,en;q=0.3
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 300
▪ The following code sample demonstrates how to get the value of the Accept-Encoding and Keep-
Alive headers:
@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String
encoding,
@RequestHeader("Keep-Alive") long keepAlive) {
}

39
Spring MVC Annotations : CookieValue
▪ The @CookieValue annotation allows a method parameter to be bound to the value of an HTTP
cookie
▪ Let us consider that the following cookie has been received with an http request:
JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84
▪ The following code sample demonstrates how to get the value of the JSESSIONID cookie:

@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@CookieValue("JSESSIONID") String cookie) {
//...
}

▪ Type conversion is applied automatically if the target method parameter type is not String

40
Spring MVC Annotations : InitBinder (1/2)
▪ Annotating controller methods with @InitBinder allows you to configure web data binding
directly within your controller class
▪ @InitBinder identifies methods that initialize the WebDataBinder that will be used to populate
command and form object arguments of annotated handler methods
▪ Such init-binder methods support all arguments that @RequestMapping supports, except for
command/form objects and corresponding validation result objects. Init-binder methods must
not have a return value. Thus, they are usually declared as void. Typical arguments include
WebDataBinder in combination with WebRequest or java.util.Locale, allowing code to register
context-specific editors

41
Spring MVC Annotations : InitBinder (2/2)
▪ The following example demonstrates the use of @InitBinder to configure a CustomDateEditor for
all java.util.Date form properties
@Controller
public class MyFormController {

@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat,
false));
}
// ...
}

42
Spring MVC Annotations
▪ To fully exploit the spring annotations add <mvc: annotation-driven /> in the Spring MVC
application context XML
▪ Although small, the <mvc:annotation-driven> tag packs a punch. It registers several features,
including JSR-303 validation support, message conversion, and support for field formatting

43
Agenda

▪ Introduction to Spring MVC


▪ Components of Spring MVC
▪ Setting up Spring MVC application
▪ Spring MVC Annotations
▪ References

44
References
▪ Spring in Action Third Edition, Craig Walls, Manning Publication
http://static.springsource.org/spring/docs/3.0.x/reference/mvc.html
▪ https://app.pluralsight.com/library/courses/springmvc-intro/table-of-contents
▪ http://krams915.blogspot.in/2012/03/spring-mvc-31-implement-crud-with_3045.html

45
CitiusTech
Markets

CitiusTech
Services

CitiusTech
Platforms

Accelerating
Innovation

Thank You CitiusTech Contacts


Email univerct@citiustech.com

www.citiustech.com

46

You might also like