Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Spring mvc
1. Hamid Ghorbani (Spring MVC) https://ir.linkedin.com/in/ghorbanihamid
1
Spring Framework
The Spring Framework is a Java platform that provides comprehensive infrastructure support for
developing Java applications. Spring was originally conceived as a way to simplify Java Enterprise Edition
(JEE) development.Benefits of Spring:
Make a Java method execute in a database transaction without having to deal with transaction APIs.
Make a local Java method an HTTP endpoint without having to deal with the Servlet API.
Make a local Java method a message handler without having to deal with the JMS API.
Make a local Java method a management operation without having to deal with the JMX API.
Framework Modules
The Spring Framework consists of features organized into about 20 modules. These modules are grouped
into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming),
Instrumentation, Messaging, and Test, as shown in the following diagram:
However, Spring is modular, allowing you to use only those parts that you need, without having to bring
in the rest.
JDK For Spring Framework:
Spring Framework 5.x JDK 8+
Spring Framework 4.x JDK 6+
Spring Framework 3.x JDK 5+
2. Hamid Ghorbani (Spring MVC) https://ir.linkedin.com/in/ghorbanihamid
2
Spring Framework Artifacts:
ArtifactId Description
spring-aop Proxy-based AOP support
spring-aspects AspectJ based aspects
spring-beans Beans support, including Groovy
spring-context Application context runtime, including scheduling and remoting abstractions
spring-context-support
Support classes for integrating common third-party libraries into a Spring application
context
spring-core Core utilities, used by many other Spring modules
spring-expression Spring Expression Language (SpEL)
spring-instrument Instrumentation agent for JVM bootstrapping
spring-instrument-
tomcat
Instrumentation agent for Tomcat
spring-jdbc JDBC support package, including DataSource setup and JDBC access support
spring-jms JMS support package, including helper classes to send/receive JMS messages
spring-messaging Support for messaging architectures and protocols
spring-orm Object/Relational Mapping, including JPA and Hibernate support
spring-oxm Object/XML Mapping
spring-test Support for unit testing and integration testing Spring components
spring-tx Transaction infrastructure, including DAO support and JCA integration
spring-web Foundational web support, including web client and web-based remoting
spring-webmvc HTTP-based Model-View-Controller and REST endpoints for Servlet stacks
spring-webmvc-portlet MVC implementation to be used in a Portlet environment
spring-websocket WebSocket and SockJS infrastructure, including STOMP messaging support
Spring Maven Dependencies:
To use the Spring repository with Maven for dependency management, add the following Maven
dependencies to your pom.xml:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
// and other dependencies . . .
3. Hamid Ghorbani (Spring MVC) https://ir.linkedin.com/in/ghorbanihamid
3
IOC and Dependency injection:
The spring-core and spring-beans modules in Core Container provide the fundamental parts of the framework,
including the IoC and Dependency Injection features. The main goal of IoC and Dependency Injection is
removing dependencies from the code. This makes the system more decoupled and maintainable.
Object Dependency:
If a class uses an instance of another class, we say the first class has a dependency on second class, for
example, a TextEditor class which uses a SpellChecker class has a dependency on SpellChecker
class(TextEditor class is dependent on SpellChecker class).
public class TextEditor {
private EnglishSpellChecker spellChecker;
public TextEditor() {
this.spellChecker = new EnglishSpellChecker();
}
}
In the above code TextEditor class is responsible for creating spellCheker object by using new operator.
This type of coding has some problems that may arise:
- Both classes are tightly coupled with each other. we cannot have a TextEditor without spellCheker
because a spellCheker object is created in a TextEditor Constructor.
- If we make any changes to spellCheker, we need to update TextEditor too.
- TextEditor controls the creation of Events. If there is any other spellChekers like
SpanishSpellCheker to be used, then we have to change TextEditor class.
To solve these problems, we need to move the control of spellCheker to other place. We call this, Inversion
of Control.
Inversion of control (IOC):
IOC is a process of taking the control of creating objects in a class (removing new() operator) and giving
it to a container. Now it’s the responsibility of the container to create object and injecting those
dependencies as required.
Java components that are instantiated by the IoC container are called beans(a bean is simply one of many
objects in your application), and the IoC container manages a bean's scope, lifecycle events, and any
AOP features for which it has been configured and coded.
4. Hamid Ghorbani (Spring MVC) https://ir.linkedin.com/in/ghorbanihamid
4
In object-oriented programming, there are several basic techniques to implement inversion of control,
one of the is dependency injection.Techniques of IOC:
- Using a factory pattern - Using a service locator pattern
- Using a contextualized lookup - Using template method design pattern
- Using strategy design pattern - Using dependency injection
Dependency injection:
Dependency Injection (DI) explains how to inject an object into a dependent class. The main idea of
dependency injection is to reduce the coupling between classes by moving the binding of objects out of
the dependent class and from compile time to runtime. There are mainly 4 ways of achieving the
Dependency Injection.
Example Of Constructor Injection:
public class TextEditor {
private IocSpellChecker spellChecker;
public TextEditor(IocSpellChecker spellChecker) {
this.spellChecker = spellChecker;
}
}
In this code example we are creating an abstraction by having the SpellChecker dependency class in
TextEditor constructor signature (not initializing dependency in class). This allows us to call the
dependency then pass it to the TextEditor class like so:
SpellChecker sc = new SpellChecker;
TextEditor textEditor = new TextEditor(sc);
Now the client creating the TextEditor class has the control over which SpellChecker implementation to
use because we're injecting the dependency to the TextEditor signature.
5. Hamid Ghorbani (Spring MVC) https://ir.linkedin.com/in/ghorbanihamid
5
IOC in Spring:
At the Core of Spring Framework, Spring IoC (Inversion of Control) is implemented using the Dependency
Injection design pattern. The Spring IoC Container creates, configures and connects the objects (which
are called Beans), then manage their life cycle. The container reads configuration metadata (XML, Java
annotations, or Java code) to know what objects to instantiate, configure, and assemble.
In Spring the org.springframework.beans and org.springframework.context packages are the
basis for Spring Framework's IoC container. There are two types of IoC containers in Spring:
BeanFactory: The BeanFactory interface is the central IoC container interface in Spring. It provides
an advanced configuration mechanism capable of managing any type of object. There are a
number of implementations of the BeanFactory interface. The most commonly used BeanFactory
implementation is the XmlBeanFactory class.
ApplicationContext: The ApplicationContext interface represents the Spring central IoC container
for providing configuration information to the application. It is child interface of
BeanFactory, provides Spring AOP features. It is responsible for instantiating, configuring, and
assembling the aforementioned beans. The default name for ApplicationContext configuration file is
applicationContext.xml.
6. Hamid Ghorbani (Spring MVC) https://ir.linkedin.com/in/ghorbanihamid
6
Spring MVC:
Spring mvc framework provides the facility to build flexible and loosely coupled web applications. MVC
stands for Model-View-Controller design pattern which separates the business logic, presentation logic
and navigation logic. The spring-webmvc module (also known as the Web-Servlet module) contains
Spring’s model-view-controller (MVC) and REST Web Services implementation for web applications. .
Also Spring can integrate effortlessly with other popular Web Frameworks like Struts, WebWork, Java
Server Faces and Tapestry.
Model: The lowest level of the pattern which is responsible for encapsulating the application data (POJO).
View: is responsible for rendering the model data to the user. The view has no knowledge of the model and business
logic and simply renders the data passed to it (as a web page, in our case).The MVC pattern also allows us to change
the view without having to change the model.
Controller: is responsible for handling all incoming HTTP requests from a web browser, building model object and
passing the model object to the view. A controller, controls the view and model by facilitating data exchange
between them.
7. Hamid Ghorbani (Spring MVC) https://ir.linkedin.com/in/ghorbanihamid
7
Containers in spring MVC:
In Spring Web Applications, there are two types of container, each of which is configured and initialized differently.
One is the "Application Context" and the other is the "Web Application Context".
ApplicationContext:
The Application Context is Spring's advanced container. It can load bean definitions, wire beans together,
and dispense beans upon request. Additionally, it has more enterprise-specific functionality such as the
ability to resolve textual messages from a properties file and the ability to publish application events to
interested event listeners.
A suggested practice is to split your application context across application layers. Breaking an application
into separate tiers helps to cleanly divide responsibility. Security-layer code secures the application, web-
layer code is focused on user interaction, service-layer code is focused on business logic, and persistence-
layer code deals with database concerns:
ContextLoaderListener is a listener to to start up and shut down Spring's application contexts. This
listener should be registered after Log4jConfigListener in web.xml, if the latter is used:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
By default, the context loader will look for a Spring configuration file at /WEB-INF/applicationContext.
xml. You can specify one or more Spring configuration files for the context loader to load by setting the
contextConfigLocation parameter in the servlet context:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/appcontext-servlet.xml,
classpath:/appcontext-security.xml,
classpath:/appcontext-service.xml,
classpath:/appcontext-persistance.xml
</param-value>
</context-param>
8. Hamid Ghorbani (Spring MVC) https://ir.linkedin.com/in/ghorbanihamid
8
WebApplicationContext:
The WebApplicationContext is an extension of the plain ApplicationContext that has some extra
features necessary for web applications. Web- related components such as controllers and view
resolvers are defined in the WebApplicationContext.
DispatcherServlet:
DispatcherServlet (part of the org.springframework.web.servlet package) is the entry point to the world
of Spring Web MVC. It essentially dispatches requests to the controllers. Spring’s DispatcherServlet is a
central Servlet (it inherits from the HttpServlet base class) that is declared in the web.xml of your web
application.
DispatcherServlet configuration in the web.xml file:
Like any servlet, DispatcherServlet must be configured in your web application’s web.xml file. On
initialization of a DispatcherServlet, the framework will look for a file named [servlet-name]-servlet.xml in
the WEB-INF directory of your web application and create the beans defined there (overriding the
definitions of any beans defined with the same name in the global scope). for example if or servlet name
is springWebApp, then DispatcherServlet will try to load the application context from a file named
springWebApp-servelt.xml:
<servlet>
<servlet-name>springWebApp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
9. Hamid Ghorbani (Spring MVC) https://ir.linkedin.com/in/ghorbanihamid
9
Next you must indicate what URLs will be handled by the DispatcherServlet. Add the following <servlet-
mapping> to web.xml to let DispatcherServlet handle all URLs that end in .jsp.
<servlet-mapping>
<servlet-name>springWebApp</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
You can change the name and location of this configuration file through a Servlet initialization parameter,
This can be configured by setting an empty contextConfigLocation servlet init parameter, as shown
below:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/myServletName.xml
</param-value>
</context-param>
<servlet>
<servlet-name>springWebApp</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>springWebApp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Most Spring MVC applications have one root context containing all service layer / DAO layer beans, and
one servlet context per spring dispatcher servlet of the application, which contains (at least) the
controllers of each servlet. The idea being that is that one application might have several servlet
dispatchers, for example one for URL /shopping/* and the other for URL /reporting/*, each with it's own
set of controllers.
10. Hamid Ghorbani (Spring MVC) https://ir.linkedin.com/in/ghorbanihamid
10
Spring mvc framework execution flow:
- First request will be received by DispatcherServlet.
- DispatcherServlet will take the help of HandlerMapping and get to know the Controller class name
associated with the given request.
- Controller process the request by calling the appropriate service method and returns a
ModeAndView object to the DispatcherServlet which contains the model data and view name.
- Now DispatcherServlet sends the view name to ViewResolver to get the actual view page.
- Finally DispatcherServlet will pass the model data to the View and render response.
Handler Mappings
HandlerMapping is an interface that defines a mapping between incoming HTTP requests and handler
objects.These handlers are typically controllers that are mapped to partial or complete URLs of incoming
requests.The handler mappings can also contain optional interceptors, which are invoked before and after
the handler. some of the implementations provided by Spring MVC are
BeanNameUrlHandlerMapping,SimpleUrlHandlerMapping, ontrollerClassNameHandlerMapping.
Example:
This Example maps requests “/simpleUrlWelcome” and “/*/simpleUrlWelcome” to the “welcome”
bean:
<bean id="urlMap" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap">
<props>
<prop key="/simpleUrlWelcome">welcome</prop>
<prop key="/*/simpleUrlWelcome">welcome</prop>
</props>
</property>
</bean>
<bean id="welcome" class="com.soshiant.WelcomeController" />
11. Hamid Ghorbani (Spring MVC) https://ir.linkedin.com/in/ghorbanihamid
11
View Resolvers:
Spring view resolvers enable you to render models in the browser without tying the implementation to a
specific view technology. The controller just handles logical names, mapping between the logical name
and the actual resource(views) is handled by the ViewResolver. Even better, controllers are completely
independent from resolvers, just registering the latter in the Spring context is enough. Spring framework
comes with quite a few view resolvers e.g. InternalResourceViewResolver, XmlViewResolver,
ResourceBundleViewResolver and a few others.
Example:
The most used resolver is InternalResourceViewResolver, which meant to forward to internal resources.
It allows us to set properties such as prefix or suffix to the view name to generate the final view page URL.
We don’t need a controller to process the request. We only need a simple jsp page, placed in the
"/webapp/pages/" folder as defined in the configuration:
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/webapp/pages/" />
<property name="suffix" value=".jsp" />
</bean>
The following code is JavaConfig of above XML example:
@Bean
public InternalResourceViewResolver myInternalViewResolver () {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/webapp/pages/");
resolver.setSuffix(".jsp");
return resolver;
}
12. Hamid Ghorbani (Spring MVC) https://ir.linkedin.com/in/ghorbanihamid
12
Spring Annotations:
Annotations are introduced from the Java 5.o release. Annotations brought one of the major change to
the Java programming style by eliminating the XML configurations and replaced with @ symbol
annotations for everything. Since then, all the major Java frameworks have started implementing the
annotations support for their release. Spring Framework has started using the annotations from the
release Spring 2.5. The following are the list of spring mvc annotations which is specific to the Spring MVC
module:
@Controller: Prior to the Spring 2.5, the controller classes are declared in the spring configuration files.
But, after the annotations style configurations, it is simplified by marking a class with @Controller
annotation to tell the Spring container that this class is a controller.
Example:
@Controller
public class WelcomeController {
. . .
}
@RequestMapping: In Spring MVC applications, the DispatcherServlet is responsible for routing
incoming HTTP requests to handler methods of controllers. When configuring Spring MVC, you need to
specify the mappings between the requests and handler methods. When configuring Spring MVC, you
need to specify the mappings between the requests and handler methods. @RequestMapping annotation
is used for mapping web requests to a specific handler classes and/or handler methods. The following
Table shows different elements of RequestMapping:
name Assign a name to this mapping.
value The primary mapping expressed by this annotation.
method The HTTP request methods to map to, narrowing the primary mapping: GET, POST, HEAD, OPTIONS,
PUT, PATCH, DELETE, TRACE.
headers The headers of the mapped request, narrowing the primary mapping.
consumes The consumable media types of the mapped request, narrowing the primary mapping.
produces The producible media types of the mapped request, narrowing the primary mapping.
path In a Servlet environment only: the path mapping URIs
params The parameters of the mapped request, narrowing the primary mapping.
Example:
@Controller
@RequestMapping(value = "/helloworld")
public class WelcomeController {
@RequestMapping(value={"","/welcome","/index"}, method = RequestMethod.GET)
public ModelAndView welcome() {
ModelAndView model = new ModelAndView("welcome");
return model;
}
}
13. Hamid Ghorbani (Spring MVC) https://ir.linkedin.com/in/ghorbanihamid
13
In the above example, request mapping is used in the class level and method level. All the requests
starting from “/helloworld” will be routed to this controller. welcome() method is accessed for the
mapping url and if the HTTP method is GET. If the POST method is used, user would see the 404
page. For the preceding code, all these URLs will be handled by welcome() method:
http://localhost:8080/helloworld
http://localhost:8080/helloworld/welcome
http://localhost:8080/helloworld/index
Example:
@RequestMapping(value="/welcome",
consumes="text/html",
produces={"application/json","application/xml"},
headers={"content-type=text/plain"}
)
public ModelAndView welcome() {
ModelAndView model = new ModelAndView("welcome");
return model;
}
Note: Since Spring MVC 4.3, you can use new annotations @GetMapping, @PostMapping,
@PutMapping and @DeleteMapping instead of standard @RequestMapping. These annotations are
standard way of defining REST endpoints. They act as wrapper to @RequestMapping:
@GetMapping = @RequestMapping(method = RequestMethod.GET).
@RequestParam: @RequestParam is annotated in the methods to bind the method parameters to the
request parameters. If the request is submitted by the browser, request parameters are passed through
the URL query parameters. That can be easily mapped to the methods by annotating the method
parameters with @RequestParam.
RequestParam Elements:
defaultValue The default value to use as a fallback when the request parameter is not provided or has an
empty value.
Name The name of the request parameter to bind to.
Value It is alias for name attribute.
required Whether the parameter is required.
Example:
Following handler method will be mapped with the following request :
‘/login?usename= myusername&password=mypassword’
14. Hamid Ghorbani (Spring MVC) https://ir.linkedin.com/in/ghorbanihamid
14
@RequestMapping(value="/login")
public ModelAndView login(
@RequestParam(value= "username",required = true) String username,
@RequestParam(value= "password",required = true) String password) {
ModelAndView model = new ModelAndView();
if (loginError != null) {
model.addObject("error", "Invalid username and password!");
}
model.setViewName("loginsuccess");
return model;
}
@ModelAttribute: The @ModelAttribute is Annotation that binds a method parameter or method
return value to a named model attribute, exposed to a web view. The annotation works only if the class
is a Controller class. @ModelAttribute can be used either as a method parameter or at the method level.
It accepts an optional “value”, which indicates the name of the attribute. If no value is supplied to the
annotation, then the value would be defaulted to the return type name in case of methods and parameter
type name in case of method-parameters.
Example:
@ModelAttribute("User")
public User getUserDetails() {
User user = new User();
user.setFirstName("your first name");
user.setLastName("your last name");
return user;
}
@RequestMapping(value="/addUser", method= RequestMethod.POST)
public ModelAndView addUser(@ModelAttribute("User") User user) {
// add user to datatbase
ModelAndView model = new ModelAndView();
model.setViewName("addUserSuccess");
return model;
}
@SessionAttribute: Starting from Spring 4.3, a new annotation @SessionAttribute was introduced.
Instead of using HttpSession object, This annotation retrieves the existing attribute from session to
a handler method parameter. This annotation has an element 'required' which is true by default. That
15. Hamid Ghorbani (Spring MVC) https://ir.linkedin.com/in/ghorbanihamid
15
means if the attribute value is not present in the session, an exception will be thrown. If we set it to false
then we can avoid the exception but the value received can be null.
Example:
@RequestMapping(value="/login", method= RequestMethod.POST)
public ModelAndView calcLoginTimout(@SessionAttribute("loginTime") DateTime loginTime) {
ModelAndView model = new ModelAndView();
if(currentTime - logintime > 10 min)
model.setViewName("logout");
return model;
}
@SessionAttributes: This annotation is used to store the model attribute in the session. The value
of this annotation is the same as value of @ModelAttribute either on method level or on handler's
method parameter level. This annotation is used at controller class level. It's used on the
@Controller class.
Example: In the following example, the user Atribute will be added to session and will be accessable
for other handler methods of LoginController class only.
@SessionAttributes("user")
public class LoginController {
@ModelAttribute("user")
public User getUserInfo() {
return new User();
}
}
16. Hamid Ghorbani (Spring MVC) https://ir.linkedin.com/in/ghorbanihamid
16
Replacing Spring XML Configuration with JavaConfig:
since version 2.5 XML is not the only way to configure spring application, but since version 3.x spring
developers has provided more and more annotations that can be used to replace all xml configurations.
On the other hand you can even develope a web mvc application without web.xml or any other servlet.xml
files. You can replace web.xml (Deployment Descriptor file) of your Java web application with a class that
extends AbstractAnnotationConfigDispatcherServletInitializer and classes with
@Configuration annotation to replace dispatcher-servlet.xml and applicationContext.xml files. You can
scan the components with @ComponentScan annotation and can use @EnableMVC annotation to enable
mvc.
@EnableWebMvc: This annotation is used for enabling Spring MVC in an application. This annotation
is equivalent to <mvc:annotation-driven /> in XML.
@ComponentScan: Spring needs to know the packages to scan for annotated components. We can
use @ComponentScan annotation to specify the base packages to scan. This annotation is equivalent to
<context:component-scan/> in XML.
@Configuration: Annotating a class with the @Configuration indicates that the class can be used by the
Spring IoC container as a source of bean definitions. This annotation comes with @Bean annotation.
@Bean: This annotation tells Spring that a method annotated with @Bean will return an object that
should be registered as a bean in the Spring application context. The method name is annotated with
@Bean works as bean ID and it creates and returns the actual bean.
Example of Spring Configuration:
@Configuration
@EnableWebMvc
@ComponentScan({"com.soshiant"})
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean
public InternalResourceViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
17. Hamid Ghorbani (Spring MVC) https://ir.linkedin.com/in/ghorbanihamid
17
WebApplicationInitializer:
WebApplicationInitializer is an interface to be implemented in Servlet 3.0+ environments in order to
configure the ServletContext programmatically. It allows for the creation, configuration, and
registration of the DispatcherServlet programmatically. Thereby allowing the web.xml file to be removed
from modern Spring MVC applications. WebApplicationInitializer implementations are detected
automatically, so you are free to package them within your application as you see fit. As an alternative to
the WebApplicationInitializer, you can also extend from AbstractDispatcherServletInitializer.
Also as an alternative to AnnotationConfigWebApplicationContext, you can also extend from
AbstractAnnotationConfigDispatcherServletInitializer
Example:
<servlet>
<servlet-name>springWebApp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/dispatcher-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springWebApp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
In this example, web.xml was successfully replaced with code in the form of a WebApplicationInitializer:
public class MyWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
AnnotationConfigWebApplicationContext rootContext = new
AnnotationConfigWebApplicationContext();
rootContext.register(AppConfig.class); // Registering config files to load at starting project
container.addListener(new ContextLoaderListener(rootContext));
AnnotationConfigWebApplicationContext dispatcherContext = new
AnnotationConfigWebApplicationContext();
dispatcherContext.register(DispatcherConfig.class);
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher",
new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
18. Hamid Ghorbani (Spring MVC) https://ir.linkedin.com/in/ghorbanihamid
18
Example of web.xml Configuration:
The DispatcherServlet acts like a front-controller and is used to dispatch the requests to the appropriate
controller methods. Since version 3.1, Spring supports using Servlet 3 API, so we can omit web.xml and
Create AppInitializer class by extending the AbstractAnnotationConfigDispatcherServletInitializer class
which is a base class for the WebApplicationInitializer. This will configure the servlet context
programatically. We need to tell it where the location of our Spring MVC Java Configuration file is located.
We do this by registering the class – of our java configuration – in the getServletConfigClasses method.
public class WebAppInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{RootConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
19. Hamid Ghorbani (Spring MVC) https://ir.linkedin.com/in/ghorbanihamid
19
Above Example on Github:
Simple welcome example with spring mvc version 4:
h ps://github.com/ghorbanihamid/SpringMVC4JavaConfigWelcomeExample
Simple login example with spring mvc version 4:
h ps://github.com/ghorbanihamid/SpringMVC4_JavaConfig_Login_Example
Simple login example with spring mvc version 5:
h ps://github.com/ghorbanihamid/SpringMVC5LoginExample
Resources:
https://docs.spring.io/spring-framework/docs/5.0.0.BUILD-SNAPSHOT/spring-framework-reference/html/mvc.html
h ps://docs.spring.io/spring/docs/4.3.12.RELEASE/spring-framework-reference/htmlsingle/
https://docs.spring.io/spring/docs/current/spring-framework-reference/overview.html
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.definition
https://spring.io/guides
https://spring.io/understanding/application-context
h ps://docs.spring.io/spring/docs/5.0.2.RELEASE/spring-framework-reference/
https://howtodoinjava.com/spring/spring-core/inversion-of-control-ioc-and-dependency-injection-di-patterns-in-spring-
framework-and-related-interview-questions/
https://www.tutorialspoint.com/spring/spring_ioc_containers.htm
https://www.javatpoint.com/ioc-container
h ps://www.java2blog.com/annota on-based-configuration-in-spring/
https://docs.spring.io/spring-framework/docs/5.0.0.BUILD-SNAPSHOT/spring-framework-reference/html/mvc.html
https://javabeat.net/spring-mvc-application-context/
https://www.dineshonjava.com/spring-web-mvc-framework-chapter-38/
https://dzone.com/refcardz/spring-annotations