Vous êtes sur la page 1sur 51

Spring MVC

Bharat Singh
27-May-2019
Agenda

What is Spring

Introduction to maven

Xml based configuration

Creating A Spring MVC Web Project using Eclipse & Maven


Introduction
 Spring is the most popular application development framework for
enterprise Java. It was initially written by Rod Johnson and was first
released under the Apache 2.0 license in June 2003.

 Spring is lightweight when it comes to size and transparency. The basic


version of Spring framework is around 2MB.

 The core features of the Spring Framework can be used in developing


any Java application, but there are extensions for building web
applications on top of the Java EE platform. Spring framework targets to
make J2EE development easier to use and promotes good programming
practices by enabling a POJO-based programming model.
Benefits of Using the Spring Framework
 Spring is organized in a modular fashion. Even though the number of
packages and classes are substantial, you have to worry only about the
ones you need and ignore the rest.

 Testing an application written with Spring is simple because


environment-dependent code is moved into this framework.
Furthermore, by using JavaBean style POJOs, it becomes easier to use
dependency injection for injecting test data

 Spring's web framework is a well-designed web MVC framework, which


provides a great alternative to web frameworks such as Struts or other
over-engineered or less popular web frameworks.
Continue……
 Spring provides a convenient API to translate technology-specific
exceptions (thrown by JDBC, Hibernate, for example) into consistent,
unchecked exceptions.

 Lightweight IoC containers tend to be lightweight, especially when


compared to EJB containers. This is beneficial for developing and
deploying applications on computers with limited memory and CPU
resources.

 Spring provides a consistent transaction management interface that can


scale down to a local transaction (using a single database, for example)
and scale up to global transactions (using JTA, for example).
How It Works
 A Spring MVC provides an elegant solution to use MVC in spring framework by
the help of DispatcherServlet. Here, DispatcherServlet is a class that receives
the incoming request and maps it to the right resource such as controllers,
models, and views.

 Model - A model contains the data of the application. A data can be a single
object or a collection of objects.

 Controller - A controller contains the business logic of an application. Here,


the @Controller annotation is used to mark the class as the controller.

 View - A view represents the provided information in a particular format.


Generally, JSP+JSTL is used to create a view page. Although spring also
supports other view technologies such as Apache Velocity, Thymeleaf and
FreeMarker.
Advantages of Spring MVC Framework
 Separate roles - The Spring MVC separates each role, where the model object,
controller, command object, view resolver, DispatcherServlet, validator, etc. can be
fulfilled by a specialized object.
 Light-weight - It uses light-weight servlet container to develop and deploy your
application.
 Powerful Configuration - It provides a robust configuration for both framework and
application classes that includes easy referencing across contexts, such as from web
controllers to business objects and validators.
 Rapid development - The Spring MVC facilitates fast and parallel development.
 Reusable business code - Instead of creating new objects, it allows us to use the
existing business objects.
 Easy to test - In Spring, generally we create JavaBeans classes that enable you to inject
test data using the setter methods.
 Flexible Mapping - It provides the specific annotations that easily redirect the page.
Spring Web MVC Framework Example
 Load the spring jar files or add dependencies in the case of Maven
 Create the controller class
 Provide the entry of controller in the web.xml file
 Define the bean in the separate XML file
 Display the message in the JSP page
 Start the server and deploy the project
Directory Structure of Spring MVC using Maven
Understanding the problem without Maven
 There are many problems that we face during the project development.
They are discussed below:
Adding set of Jars in each project: In case of struts, spring, hibernate
frameworks, we need to add set of jar files in each project. It must
include all the dependencies of jars also.
Creating the right project structure: We must create the right
project structure in servlet, struts etc, otherwise it will not be
executed.
Building and Deploying the project: We must have to build and
deploy the project so that it may work.
What it does
 Maven simplifies the above mentioned problems. It does mainly following
tasks.
It makes a project easy to build
It provides uniform build process (maven project can be shared by all
the maven projects)
It provides project information (log document, cross referenced
sources, mailing list, dependency list, unit test reports etc.)
It is easy to migrate for new features of Maven
We can add jars and other dependencies of the project easily using the
help of maven.
Maven is very helpful for a project while updating central repository of
JARs and other dependencies.
Using maven we can easily integrate our project with source control
system (such as Subversion or Git).
 Maven, a Yiddish word meaning accumulator of knowledge.
 Apache Maven is a software project management and comprehension
tool. Based on the concept of a project object model (POM), Maven can
manage a project's build, reporting and documentation from a central
piece of information.
 Maven’s primary goal is to allow a developer to comprehend the complete
state of a development effort in the shortest period of time. In order to
attain this goal, there are several areas of concern that Maven attempts to
deal with:
 Making the build process easy
 Providing a uniform build system
 Providing quality project information
 Providing guidelines for best practices development
 Allowing transparent migration to new features
Standard Maven project structure
 The src/main/java directory contains the project source code,
the src/test/java directory contains the test source, and
the pom.xml file is the project's Project Object Model, or POM.

The POM
 The pom.xml file is the core of a project's configuration in Maven. It is a
single configuration file that contains the majority of information
required to build a project in just the way you want. The POM is huge
and can be daunting in its complexity, but it is not necessary to
understand all of the intricacies just yet to use it effectively. This
project's POM is:
How maven works
Core Concepts of Maven:
 POM Files: Project Object Model(POM) Files are XML file that contains
information related to the project and configuration information such as
dependencies, source directory, plug-in, goals etc. used by Maven to build
the project. When you should execute a maven command you give maven
a POM file to execute the commands. Maven reads pom.xml file to
accomplish its configuration and operations.
 Dependencies and Repositories: Dependencies are external Java libraries
required for Project and repositories are directories of packaged JAR files.
The local repository is just a directory on your machine hard drive. If the
dependencies are not found in the local Maven repository, Maven
downloads them from a central Maven repository and puts them in your
local repository.
 Build Life Cycles, Phases and Goals: A build life cycle consists of a
sequence of build phases, and each build phase consists of a sequence of
goals. Maven command is the name of a build lifecycle, phase or goal. If a
lifecycle is requested executed by giving maven command, all build phases
in that life cycle are executed also. If a build phase is requested executed,
all build phases before it in the defined sequence are executed too.
 Build Profiles: Build profiles a set of configuration values which allows you
to build your project using different configurations. For example, you may
need to build your project for your local computer, for development and
test. To enable different builds you can add different build profiles to your
POM files using its profiles elements and are triggered in the variety of
ways.
 Build Plug-ins: Build plug-ins are used to perform specific goal. you can
add a plug-in to the POM file. Maven has some standard plug-ins you can
use, and you can also implement your own in Java.
Elements used for Creating pom.xml file
 Project- It is the root element of the pom.xml file.
 ModelVersion- means what version of the POM model you are using.
Use version 4.0.0 for maven 2 and maven 3.
 A groupId- means the id for the project group. It is unique and Most
often you will use a group ID which is similar to the root Java package
name of the project like we used the groupId com.project.loggerapi.
 ArtifactId- used to give name of the project you are building.in our
example name of our project is LoggerApi.
 Version- contains the version number of the project. If your project has
been released in different versions then it is useful to give version of
your project.
Other Elements of Pom.xml file
 Dependencies - is used to defines a list of dependency of project.
 Dependency- defines a dependency and used inside dependencies tag.
Each dependency is described by its groupId, artifactId and version.
 Name- element is used to give name to our maven project.
 Scope- element used to define scope for this maven project that can be
compile, runtime, test, provided system etc.
 Packaging- element is used to packaging our project to output types like
JAR, WAR etc.
Xml based configuration
 The /WEB-INF/web.xml file is used to define how to deploy the web module
to a Servlet container like JBoss, Tomcat, Glassfish or any other servlet
container. It is a part of the Java Servlet specification. The file name and
locations cannot be changed.
 Basically web.xml tell container all servlets in the web application
with <servlet> element , then tell container when to use which servlet by the
url mapping with <servlet-mapping> element.
 In Spring MVC project, for most cases, there is only one
servlet org.springframework.web.servlet.DispatcherServlet.
 Let this DispatcherServlet handle all the requests. After container hands over
the request to DispatcherServlet, the income http request formally enters the
Spring world. A controller will be chosen to handle the request according to
@RequestMapping.
What is context configuration xml
 In XML style configured Spring MVC project, there will be at least one xml to
configure Spring MVC WebApplicatonContext. As Spring document says, there are
2 type of WebApplicationContext:
 Root WebApplicationContext
 Servlet WebApplicationContext
 All servlets, althrough in most case only one DispatcherServlet, share root
context. Each Servlet has its private context. Spring tries to locate a bean first in
Servlet context, if not found, then search root context. A Spring MVC project can
use both or just any one of them.
 The default configuration file for root WebApplicatonContext is /WEB-
INF/applicationContext.xml
 The default configuration file for servlet WebApplicatonContext is /WEB-
INF/[servletName]-servlet.xml
 The files’ name and location can be changed in web.xml.
 The job of the DispatcherServlet is to take an incoming URI and find the
right combination of handlers (generally methods on Controller classes)
and views (generally JSPs) that combine to form the page or resource
that's supposed to be found at that location.
A project might have
 a file /WEB-INF/jsp/pages/Home.jsp
and a method on a class
 @RequestMapping(value="/pages/Home.html")
private ModelMap buildHome() {
return somestuff;
}
What is Spring DispatcherServlet
 DispatcherServlet acts as front controller for Spring based web
applications. It provides a mechanism for request processing where actual
work is performed by configurable, delegate components. It is inherited
from javax.servlet.http.HttpServlet, it is typically configured in
the web.xml file.
 A web application can define any number of DispatcherServlet instances.
Each servlet will operate in its own namespace, loading its own application
context with mappings, handlers, etc. Only the root application context as
loaded by ContextLoaderListener, if any, will be shared. In most cases,
applications have only single DispatcherServlet with the context-root
URL(/), that is, all requests coming to that domain will be handled by it.
 DispatcherServlet uses Spring configuration classes to discover the
delegate components it needs for request mapping, view resolution,
exception handling etc.
How it uses Web Application Context
 how dispatcher servlet works internally? In a Spring-based application, our
application objects live within an object container. This container creates
objects and associations between objects, and manages their complete life
cycle. These container objects are called Spring-managed beans (or simply
beans), and the container is called an application context (via
class ApplicationContext) in the Spring world.
 WebApplicationContext is an extension of a plain ApplicationContext. it is
web aware ApplicationContext i.e it has Servlet Context information.
When DispatcherServlet is loaded, it looks for the bean configuration file
of WebApplicationContext and initializes it.
 By having access to Servlet context, any spring bean which
implement ServletConextAware interface – can get access
to ServletContext instance and do many things with it. For example, it can
get context init parameters, get context root information and get resources
location inside web application folders.
DispatcherServlet XML based Configuration
 how a typical DispatcherServlet declaration and initialization looks like.
web.xml
<web-app>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet-context.xml</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher-servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher-servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
 In above code, dispatcher-servlet-context.xml file will contain all beans definitions and
associations which will be available to DispatcherServlet. These bean definitions will
override the definitions of any beans defined with the same name in the global scope.
e.g. applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
A Spring MVC Web Project
Thank You !!!

Vous aimerez peut-être aussi