DispatcherServlet and ContextLoaderListener in Spring MVC Explained
There are times when you might have been thinking what is this ContextLoaderListener and why do we use it or should we use it or not while configuring your spring web MVC application like we explained in our previous article . In this article we will try to answer all these questions.
In an spring MVC application there are usually two bean containers.
1. One is Application Context which is created by ContextLoaderListener2. Another is Web Application Context which is created by the DispatcherServlet
Both of these bean containers gets their bean configurations from the xml files defined in web.xml file, or if we are using java based configuration with Servlet 3.0 or above we define the configuration in java configuration file inside a WebInitializer class like we explained in our previous article
n this article we will see what is the difference between these two bean containers, what is the relation between these bean containers and which one should be used when ?
1. Application Context Created by ContextLoaderListener
Configuration and use of ContextLoaderListener<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:app-context.xml</param-value> </context-param>
As we can see we define the configuration file for loading beans for Application Context created by ContextLoaderListener as the context param in web.xml, which is app-context.xml in above example in the classpath.
There is only one application context per application and we should define the beans in this container which are common and we want them to be accessible throughout our application. This is considered a good practice to define data tier beans and service tier beans in Application Context.
There are some applications where we might need more than one Dispatcher Servlet then this Application Context can be used to get the common beans for the Dispatcher Servlets because it serves the whole application.
2. Application Context DispatcherServlet
Configuration and use of DispatcherServlet<servlet> <servlet-name>user-servlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:user-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
In an application each dispatcher servlet creates its own bean container which is Web Application Context.
We define the path of configuration file for Web Application Context to load the beans as init param of the servlet as we have defined above.
Note : Important thing here is this that the name of the configuration file must be of form - *-servlet.xml
Web Application Context is a child context of Application Context created by ContextLoaderListener
Because Web Application Context is a child context of the Application Context created by ContextLoaderListener therefore beans in the application context can be referred by Web Application Context, this is the reason it is recommended to put common beans like data-tier beans and service tier beans in Application so that any Web Application Context can use them
Loading Configuration for DispatcherSrvlet and ContextLoaderListener without web.xml and with Servlet 3.0 or above
If you are using Servlet API 3.0 or above you can choose to skip the use of web.xml file. We create a Initializer class which extends AbstractAnnotationConfigDispatcherServletInitializer and then implementing its method we can define the configuration java files to load beans.
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[] {"/"};
}
}
In above class method getRootConfigClasses() returns an array of java configuration classes which will be used by ContextLoaderListener to load the beans which is RootConfig.class in the example above. getServletConfigClasses() returns an array of java configuration classes which will be used by DispatcherServlet to load the beans which is WebConfig.class in the example above.
For getting more detailed information about how to setup an Spring MVC application without the use of web.xml , click on this article
Also in case of any doubt or query feel free to leave a comment below, Thanks !
Accepting Request Input using @RequestParam, @PathVariable and Form Handeling Spring MVC
In our last SPRING MVC article we explained you how you can create and dynamic Spring MVC web project with MAVEN without using web.xml with java based configuration and also explained you the flow of request through dispatcher servlet to controller and then back to view.
But any web application is not complete if it cannot accept input from the client. So in this article we will show you how you can get the input from the client using Spring MVC
Spring MVC provides three ways in which you can get the input from a by request from a client inside a controller method.
1. By Request Parameters 2. By Path Variables 3. Form Parameters1. Getting Input from request parameters with @RequestParam
Suppose we are making a GET request which has url like - /home?userId=123
Then in this url userId is the request parameter with value 123.
And to capture this value in our @Controller annotated method we use @RequestParame annotated method parameter as shown in the example below.
@RequestMapping(value= "/home", method=RequestMethod.GET)
public String home (@RequestParam("userId") int id){
System.out.println(id);
return "home";
}
Now if controller gets a request with query parameter with name userId it will be captured by id variable which is of type int.
Using default value for @RequestParamWe can also define a default value for @RequestParam annotated variable using defaultValue as shown in the next example.
@RequestMapping(value= "/home", method=RequestMethod.GET)
public String home (@RequestParam(value="userId", defaultValue="255") int userId){
System.out.println(userId);
return "home";
}
So if we do not provide any query parameter just simple /home url then userId variable will have a default value 255. We have provided 255 as a String because query parameters are always of type String , but later it will get converted into int because userId variable is an int.
2. Getting Values from request as Path Variable using @PathVariable
Path variables are another way of getting data as path variable, here in the url we do not use key value pair like query parameter to pass the value but the value is sent as the part of the url path.
Like for url - /home/jonney
Here we can get the name jonney as part variable in spring controller using @PathVariable annotated method parameter.
For identifying the variable portion of the Url path we use a variable inside the url of the @RequestMapping annotated url, which is surrounded by curly braces.
For url - /home/jonney , to get the path variable jonney we can use the following controller method.
@RequestMapping(value= "/home/{userName}", method=RequestMethod.GET)
public String home (@PathVariable("userName") String name){
System.out.println(name);
return "home";
}
In above example name String parameter has been used to capture the path variable which has been passed to the variable part of @RequestMapping url {userName}
3. Accessing The Form Data In Spring MVC
There are two parts of this process, first is to display the form with some object bound to the form and other is getting the values from the form after form is submitted.
To bind the data of form to an object we will send an empty Object say User in model and bind the form with this Object using modelAttribute
Controller method for Displaying the form -
@RequestMapping(value="register-emp", method=RequestMethod.GET)
public ModelAndView registerEmployeeForm(){
ModelAndView model = new ModelAndView("register_employee", "user", new Employee());
return model;
}
In above method we are sending an Employee class Object with Model as attribute name 'user' and the view name is 'register_employee'
register_employee.jsp<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <div style="text-align:center"> <form:form method="post" modelAttribute="user"> <table> <tr> <td>User Name</td> <td><form:input path="name" type="text" /> <!-- bind to user.name--></td> </tr> <tr> <td>User Email</td> <td><form:input path="email" type="text" /> <!-- bind to user.email--></td> </tr> <tr> <td>User Phone</td> <td><form:input path="phone" type="number" /> <!-- bind to user.name--></td> </tr> <tr> <td>User Password</td> <td><form:input path="password" type="password" /> <!-- bind to user.name--></td> </tr> <tr> <td><button type="submit">SUBMIT</button> <!-- bind to user.name--></td> </tr> </table> </form:form> </div>
As you can notice from above form we have not used action attribute because we want to submit the form to the same url.
Controller Method to get the form Values
@RequestMapping(value="register-emp", method=RequestMethod.POST)
public ModelAndView registerEmployee(@ModelAttribute("user") Employee emp){
ModelAndView model = new ModelAndView("emp_details");
model.addObject("user", emp);
return model;
}
As you can see we have used @ModelAttribute annotated method parameter, this is used to get the Model attribute with key ‘user’ which is obviously the user object we want to access.
After we get the values we are sending it to another jsp emp_details.jsp with model to show them.
For any questions or query, feel free to leave comments below. Thanks!
Create Spring MVC web application without web.xml and with Java Configuration using MAVEN
First of All we have to create a web project which we will create with the help of maven tool. We will not go into the details of creating a web project with MAVEN in eclipse, just follow the given steps below to create a WEB project with MAVEN
* First of all open the command line and check whether MAVEN is installed or notmvn -v
if you see the following line, then follow the next steps, otherwise install maven first.Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T22:11:47+05:30) Maven home: C:\maven\apache-maven-3.3.9\bin\.. Java version: 1.7.0_79, vendor: Oracle Corporation Java home: C:\Program Files\Java\jdk1.7.0_79\jre Default locale: en_IN, platform encoding: Cp1252 OS name: "windows 7", version: "6.1", arch: "amd64", family: "windows"
* Type the following command for creating the project folder at the current location
C:\Users\jonney\maven-project>mvn archetype:generate -DgroupId=com.tutorials.sample -DartifactId=SampleSpringMaven -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false* Once the project folder is created, step inside the folder and type the following command for making it importable in eclipse
C:\Users\jonney\maven-project\SampleSpringMaven>mvn eclipse:eclipse -Dwtpversion=2.0* Now import the project in your eclipse and open the pom.xml for adding dependencies for the project. Update the pom.xml as given below.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorials.sample</groupId>
<artifactId>SampleSpringMaven</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>SampleSpringMaven Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>4.2.4.RELEASE</spring.version>
<jdk.version>1.7</jdk.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
<build>
<finalName>SampleSpringMaven</finalName>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<url>http://localhost:8080/manager/text</url>
<server>my-tomcat</server>
<path>/SampleSpringMaven</path>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
* Once you are done with adding dependencies, again type in the following command for downloading and adding dependencies in the project.
C:\Users\jonney\maven-project\SampleSpringMaven>mvn eclipse:eclipse -Dwtpversion=2.0
Now you are ready to start developing your project in eclipse.
Note :If you are using servlet 3.0 or above then you can skip web.xml file and configure all the configurations inside a java file, this is the must requirement if you want to skip web.xml.
Before we start writing any code lets understand the flow of the application and its components -
1. When application gets a request from some client , it goes to the DispatcherServlet which works as a front end controller and based on the url of the request , it forwards the request to the Spring MVC controller.
2. Spring MVC controller gets the request and based on the url of the request one of its method gets called , here request can leave its payload for some time and so that controller can perform some business calculations using service classes. After different operation are done, controller sends a logical view name wrapped with some data which we want to show the user and sends it back to the dispatcher servlet.
3. Now controller consults the ViewResolver and gives the logical view name to the ViewResolver which then gets resolved into some jsp or html, this is the last stop of the request and the data gets rendered by the view.
Now we will see how all these above steps are performed one by one write our application for showing the home page of application.
Setting up Dispatcher Servlet without web.xml file
In spring web projects Dispatcher Servlet works as a single from end controller and based on the url of the coming http request it distributes the requests to different mvc controllers. Since we are not using web.xml file here so we will configure this servlet in a java class WebAppInitializer and this class will extend AbstractAnnotationConfigDispatcherServletInitializer. Any class that extends AbstractAnnotationConfigDispatcherServletInitializer is automatically used to configure DispatcherServlet and Spring application context in application’s servlet context.
WebAppInitializer.java
package com.hellospring.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
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[] {"/"};
}
}
As we can see that WebAppInitializer has two methods for configuring java configuration classes.
When DispatcherServlets starts it creates an spring application context and this application context loads its configuration from WebConfig.class which has been provided by getServletConfigClasses() method declared above in WebAppInitializer class.
But in spring web application one another Application context is created by ContextLoader- Listener and this Application context loads its configurations from RootConfig.class class provided by the method getRootConfigClasses() defined above.
DispatcherServlet is supposed to load beans basically for web components like controllers and view resolvers , whereas ContextLoader listener is expected to load other beans usually data-tier beans and and middle-tier beans.
And the last method provides the url which needs to be associated with the dispatcher servlet
Now we are done with creating a dispatcher servlet for our web application, but what about enabling mvc and component scanning which we used to do in our configuration files earlier ?
@EnableWebMvc - Annotate your configuration class with this annotation to enable annotation driven Spring MVC in your application.
@ComponantScan(“package”) - Annotate your java config class with this annotation to enable component scanning for the package.
package com.hellospring.config;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.hellospring.model, com.hellospring.web")
public class AppConfig extends WebMvcConfigurerAdapter {
@Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
In above configuration class we have annotated the class with @Configuration
@EnableWebMvc and @ComponentScan and the purpose has already been explained.
We have also defined a ViewResolver bean which we used to define in an xml file earlier.
Now another thing to notice is this, that we have extended WebMvcConfigurerAdapter which allow us to override configureDefaultServletHandling() method. By overriding this method we are saying the DispatcherServlet to forward the requests for static resources to the default servlet of servlet container.
Now as we are done with writing our configuration file, let’s take our request one step forward which is a controller.
Writing a Simple Controller
In spring MVC controller is noting but just a simple java class annotated with @Controller mapping and methods annotated with @RequestMapping.
Given below we have written a simple controlled for our home page of our application.
package com.hellospring.web.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.hellospring.web.service.CommonService;
@Controller
public class HomeController {
@RequestMapping(value = "/home", method = RequestMethod.GET)
ModelAndView home (){
return “home”;
}
}
@Controller - We have annotated our Class with this mapping to make sure that this class gets defined as a bean in our Application context. We can also use @Component annotation to define a class as a bean in application but using the @Controller annotation gives extra information about what kind of component this class is.
@RequestMapping - In this method we have defined the url for which this method will be called and the type of HTTP method which is GET in this case.
@RequestMapping(“home”,”welcome”)-
We can also define multiple urls for which this method will get called, because it can take an array of strings
@RequestMapping("/home") - We can also set class level mapping which will be used for all the methods inside that controler. Just annotate the class with @RequestMapping annotation like methods.
Rendering the View
As we can see that the only method inside the controller class is not doing much except returning a string “home”. This is the logical view name which will be provided to ViewResolver which we have configured as a bean in WebConfig configuration file. And as we can see in the ViewResolver configuration this view name will be resolved as a jsp at /WEB-INF/jsp/home.jsp.
This is a simple jsp file for now just Welcoming User.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ page session="false" %> <html> <head> <title>Home Page</title> </head> <body> <h1>Hello, Welcome User</h1> </body> </html>
Passing Data To View
In above controller , we are not sending anything to the jsp we are sending a logical view name to the view resolver which is rendering the jsp page, but in real world applications this very unlikely. To bind the data to the view there are various methods but the one which we are going to use is easy and used most of the time.
We create a ModelAndView object in the controller , which is nothing special but a simple map of key and values, which we want to send to the View. And if the view is a Jsp , the model data is copied into the request as the request attributes. Now because the modal data is now accessible as request attributes so we can easily use it in jsp using JSTL or el.
Controller Version 2
package com.hellospring.web.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.hellospring.web.service.CommonService;
@Controller
public class HomeController {
@RequestMapping("/home")
ModelAndView home (){
ModelAndView model = new ModelAndView("home");
model.addObject("userName", “JOHN WICK”);
return model;
}
}
The above method binds a string “JOHN WICK” with key “userName” and set the view name “home” As an argument to the ModelAndView constructor. Now this data can be rendered on /WEB-INF/jsp/home.jsp page
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>Hello, Welcome <c: out value=${userName}></h1>
</body>
</html>
home page with SimpleController,
home page with SimpleController and model data,So, this was all about setting up Spring MVC project with Servlet 3 and with JAVA config./p>