Spring MVC - Spring MVC Introduction
In this example we will give you quick overview of Spring MVC Framework. The Spring MVC framework is the MVC stack for the development of web applications based Model View Controller (MVC) architecture.
What is MVC architecture?
The MVC or Model View Controller architecture is famous design pattern used in designing the applications. This design pattern separates the application into three parts called Model, View and Controller.
Model: Model is the business data or simple the data of the application.
View: View is the presentation part of the application such as data entry form, reports etc.
Controller: The controller component delegates between Model and view.
Spring MVC
The Spring Framework is light-weight container and it supports multiple frameworks and libraries. The Spring framework allows the developers to mix and match multiple frameworks while developing and deploying the applications. The Spring MVC takes the advantage of Spring framework and provides once to best and productive framework for development of web applications.
The Spring MVC is a web development framework based on the MVC (Model View Controller) design pattern. The features of Spring MVC framework are the Pluggable View technology and Injection of services into controllers. Let's see in detail:
Pluggable View technology
There are many view technologies such as JSP, Tiles, Velocity etc. Spring framework allows us to use these view technologies.
Injection of services into controllers
The IoC container provides the important functionality of the dependency injection. This helps the programmer to inject the dependency such as business service at runtime. This saves lot of code duplication and coding effort.
Spring's MVC components:
Model:
The class org.springframework.ui.ModelMap is used by the spring framework to hold the data. It wraps the business data into org.springframework.ui.ModelMap class and then pass it to the view.
View:
Framework provides pluggable view, and it allows the developers to create views using jsp, Velocity and Jasper templates. In Spring MVC Logical view and Model are represented in the object of the classorg.springframework.web.servlet.ModelAndView.
Controller:
The controller is responsible for handling all the requests from the user and then process the user request. Here are the list of controllers available in the Spring 2.5 framework:
1. SimpleFormController
2. AbstractController
3. AbstractCommandController
4. CancellableFormController
5. AbstractCommandController
6. MultiActionController
7. ParameterizableViewController
8. ServletForwardingController
9. ServletWrappingController
10. UrlFilenameViewController
11. AbstractController
12. AbstractCommandController
13. SimpleFormController
14. CancellableFormController.
In the next sections we will see the examples of all these controllers.
How Spring MVC Works
How Spring MVC Works?
In this we will see the request flow for the spring framework. We will also show you the request flow diagram illustrating the working of Spring MVC module.
The Spring MVC modules comes with the Spring Framework distribution. The Spring MVC modules of the Spring Framework well integrates with rest of the framework. This modules is also very extensible.
Spring MVC is based on the MVC design pattern. Here is the list of key classes of Spring MVC.
• DispatcherServlet
The DispatcherServlet is configured in the web.xml file and required URL patterns are mapped to this Servlet. It works as the front controller and handle all the request from the user.
• ModelAndView
This class works as the holder for both Model and View in the Spring MVC.
• SimpleFormController
The SimpleFormController is the Concrete FormController implementation. It provides the configurable form and success views, and an onSubmit chain for convenient overriding. Automatically resubmits to the form view in case of validation errors, and renders the success view in case of a valid submission.
Simplified Spring MVC architecture diagram
Following diagram shows the simplified architecture of Spring MVC:
Let's understand the sequences of the events happens when a request is received by the Spring MVC. Following events happens when DispatcherServlet receives are request:
1. The DispatcherServlet configured in web.xml file receives the request.
2. The DispatcherServlet finds the appropriate Controller with the help of HandlerMapping and then invokes associated Controller.
3. Then the Controller executes the logic business logic (if written by the programmer) and then returns ModeAndView object to the DispatcherServlet.
4. The DispatcherServlet determines the view from the ModelAndView object.
5. Then the DispatcherServlet passes the model object to the View.
6. The View is rendered and the Dispatcher Servlet sends the output to the Servlet container. Finally Servlet Container sends the result back to the user.
Request flow in Spring MVC
Spring MVC is request driven and DispatcherServlet handles the request from client and then dispatches the request to controllers. It tightly integrates with the Spring IoC container and allows the developers to use every features of Spring framework.
The following diagram illustrates the request flow in Spring MVC.
Request handling steps in Spring MVC
1. Client access some URL on the server.
2. The Spring Front Controller (DispatcherServlet) intercepts the Request. After receiving the request it finds the appropriate Handler Mappings.
3. The Handle Mappings maps the client request to appropriate Controller. In this process framework reads the configuration information from the configuration file or from the annotated controller list. Then DispatcherServlet dispatch the request to the appropriate Controller. The Handler Adapters involves in this process.
4. Then the Controller processes the Client Request, it executes the logic defined in the Controller method and finally returns the ModelAndView object back to the Front Controller.
5. Based on the values in the ModelAndView Controller resolves the actual view, which can be JSP, Velocity, FreeMaker, Jasper or any other configured view resolver.
6. Then the selected view is rendered and output is generated in the form of HttpServletResponse. Finally Controller sends the response to the Servlet container, which sends the output to the user.
In the next section we will see the controller stack in Spring MVC
Spring MVC Controllers - Controllers hierarchy in Spring MVC
Controllers hierarchy in Spring MVC
In this we will will understand the controllers hierarchy in Spring MVC Module. The Spring MVC module provides a lot of flexibility to easily develop MVC based web applications. It provides many controllers that can be used to achieve different jobs.
Spring MVC module is based on the MVC design pattern. The main components involved are DispatcherServlet, Controller and Views. In Spring MVC DispatcherServlet plays very important role. It handles the user request and delegates it with Controller. Following diagram shows the very simplified architecture:
In this Spring MVC, DispatcherServlet works as the controller and it delegates the request to the Controller. Developers extends the abstract controller provided by the framework and writes the business logic there. The actual business related processing is done in the Controller.
Spring MVC provides many abstract controllers, which is designed for specific tasks. Here is the list of anstract controllers that comes with the Spring MVC module:
1. SimpleFormController
2. AbstractController
3. AbstractCommandController
4. CancellableFormController
5. AbstractCommandController
6. MultiActionController
7. ParameterizableViewController
8. ServletForwardingController
9. ServletWrappingController
10. UrlFilenameViewController
11. AbstractController
12. AbstractCommandController
13. SimpleFormController
14. CancellableFormController.
Following diagram shows the Controllers hierarchy in Spring MVC:
In the next sections we will be learning about all these controllers. We will also provide you the examples codes illustrating the usage of these controllers.
Spring MVC Getting Started - Getting started with Spring MVC
Starting the development using Spring MVC Framework
In this we will quickly start developing the application using Spring MVC module. We will also see what all configuration and code is to be developed. We we will also see how to compile, run the example program.
We will first develop a simple Spring MVC Hello World example and then test on the Tomcat server.
What is required?
In order to complete the tutorial you will need the following software and libraries.
1. JDK 1.5 or above
2. Eclipse IDE 3.3 or above
3. Tomcat 6 or later
4. Spring framework 2.5 or above
Getting stated:
Please make sure that JDK is installed on your computer. Check your Eclipse IDE version, if it is not 3.3 or above download it from the official website at http://www.eclipse.org/downloads/. Also download Spring 2.5.
Understanding the example:
We are going to develop a very simple example that will just print "Hello World" message on the browser. We will use Eclipse IDE to develop run and test the application.
We will have to follow the following steps:
1. Create new dynamic web application in eclipse.
2. Setup tomcat as container to run the application.
3. Add Spring libraries to the project.
4. Add necessary configuration in web.xml file.
5. Create Controller class.
6. Create dispatcher-servlet.xml and add required mapping the xml file.
7. Create JSP file to display "Hello World" message.
8. Finally run tomcat and deploy the application on the tomcat.
9. And check application in web browser.
In the next section we will create new project in eclipse and add spring libraries.
Spring MVC Hello World Example in Spring 2.5
In this tutorial we will develop the Spring MVC Example and then run on the Tomcat server.We are using Spring 2.5 for this tutorial. We will also explain you the process of creating the dynamic web application in Eclipse IDE version 3.5.2. We will use tomcat to run the example. Eclipse provides the way to easily run the example from the IDE.
Step 1:
The initial step is to create Dynamic Web Project in eclipse. To create a new Dynamic project in Eclipse IDE select File -> Dynamic Web Project as shown below.
Step 2:
After that New Dynamic Project Window will appear on the screen and you will enter the web application name in the Project name text box. Enter Hello World in the Project Name and then click Next button.
We will enter the project name and set the project location and set the target runtime (Apache Tomcat server) just click on New button after that a New Server Runtime Environment window will appear, select the latest version of runtime environment and click Next button and Download and install the Tomcat Server and click on Finish button and also click on Finish button in Dynamic Web Project creation window.
Step 3:
After that we will set the nature of the project just right click on the project and select Spring Tools with Add Spring Project Nature.
Step 4:
We will add all Spring Web MVC 2.5 jar files.
After that Build Path window will appear on the IDE screen look like
After that we will select the Libraries tab and click on Add External Jars button for add jar files. After selecting all Spring 2.5 Web MVC jar file we will click on Ok button and jar files is appears in your project lib folder.
Now your project will created in Eclipse IDE.
Step 5:
Now we will created a index.jsp in project's WebContent folder. In the jsp file we will create a new hyperlink "Hello World !" that will be linked to hello.html page. The code of index.jsp is:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<body>
<a href="hello.html">Hello World</a>
</body>
</html>
Step 6:
Now we will configure the DispatcherServlet in web.xml file. The DispatcherServlet will be configured to process all the request ending with .html.
Here is the code of configuring DispatcherServlet in web.xml file:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
The full code of web.xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd" >
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Step 7:
Now we will create a new xml file called dispatcher-servlet.xml in the WEB-INF folder of the web application. This is the main configuration file for the Spring MVC. Here we will define the ViewResolver, the code for defining the view resolver is as shown below:
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
The view resolver looks for the jsp files in the /WEB-INF/jsp/ directory.
The we have to define bean fororg.springframework.web.servlet.handler.SimpleUrlHandlerMapping as shown below:
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
Then we will define the url mapping with the Controller bean as shown below:
<map>
<entry key="/hello.html">
<ref bean="helloController"/>
</entry>
</map>
Finally we will define the Controller bean as shown below:
<bean id="helloController" class="net.roseindia.web.HelloWorldController"></bean>
The full code of dispatcher-servlet.xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org
/schema/beans/spring-beans-2.5.xsd"
xmlns:p="http://www.springframework.org/schema/p">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref local="localeChangeInterceptor"/>
</list>
</property>
<property name="urlMap">
<map>
<entry key="/hello.html">
<ref bean="helloController"/>
</entry>
</map>
</property>
</bean>
<bean id="helloController" class="net.roseindia.web.HelloWorldController"> </bean>
<bean id="localeChangeInterceptor" class="
org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="hl"/>
</bean>
<bean id="localeResolver"class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>
</beans>
Step 8:
After that we will creates the controller class in the project src folder. This will be used as the controller for the hello.html request. The code of the HelloWorldController.java calss is:
package net.roseindia.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class HelloWorldController implements Controller {
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String Mess = "Hello World!";
ModelAndView modelAndView = new ModelAndView("hello");
modelAndView.addObject("message", Mess);
return modelAndView;
}
}
After that we will create a hello.jsp in the WEB-INF folder by create a jsp folder. The WEB-INF/jsp/hello.jsp code is:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<c:out value="${message}"/>
</body>
</html>
Step 9:
To run the example select Run -> Run As -> Run On Server from the menu and then run the application on tomcat server. Eclipse will start Tomcat server and deploy the application on the Tomcat. Ellipse will also open the application in it internal browser as shown below:
Click on the "Hello World" link to test the application. It should display the "Hello World" message as shown below.
Say Hello application in Spring 2.5 MVC
This application will help you in getting started with the development of form based application in Spring MVC. You will learn how to create form and then retrieve the form data in another controller.
In this tutorial we will create a web application that will present a form to the user. Then user can enter some and press "Save" button. Then application displays name with "Hello" message. For example we will enter name "Brijesh" then the application will display with "Hello Brijesh".
Step 1:
Now we will create a index.jsp in project's WebContent folder. In the index.jsp file we will create a hyperlink "Say Hello" that will be linked "entername.html" file. The code of the index.jsp is:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<body>
<a href="entername.html">Say Hello</a>
</body>
</html>
Step 2:
Now we will configure the DispatcherServlet in web.xml. The full code of the web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd" >
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>/spring</taglib-uri>
<taglib-location>/WEB-INF/spring.tld</taglib-location>
</taglib>
</web-app>
In this web.xml we have to used <taglib></taglib> tag for include the spring.tld file in this application. These <taglib></taglib> contains two tags one is <taglib-url> that gives a url for access the spring tag library and other is <taglib-location> tag that told us where is spring.tld file.
Step 3:
Now we will create a dispatcher-servlet.xml in the WEB.INF folder that is the main configuration file for this application. This file contains the all configuration beans for this application. The code of thedispatcher-servlet.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org
/schema/beans/spring-beans-2.5.xsd"
xmlns:p="http://www.springframework.org/schema/p">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref local="localeChangeInterceptor"/>
</list>
</property>
<property name="urlMap">
<map>
<entry key="/entername.html">
<ref bean="enternameController"/>
</entry>
</map>
</property>
</bean>
<bean id="userValidator" class="net.roseindia.web.UserValidator"/>
<bean id="enternameController" class="net.roseindia.web.UserFormController">
<property name="sessionForm"><value>false</value></property>
<property name="commandName"><value>user</value></property>
<property name="commandClass"><value>net.roseindia.web.User</value></property>
<property name="validator"><ref bean="userValidator"/></property>
<property name="formView"><value>entername</value></property>
<property name="successView"><value>sayhello</value></property>
</bean>
<bean id="localeChangeInterceptor" class="
org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="hl"/>
</bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>
</beans>
This file contains the urlMapping for the entername.html file and configure the controller for this file. It have also configure Validator, commandClass, commandName, formView, and successView etc.
The validator property gives the permission to set validator for the perticular request and add the validator class with this request controller. This is the code for UserValidator.java:
<bean id="userValidator" class="net.roseindia.web.UserValidator"/>
<bean id="enternameController" class="net.roseindia.web.UserFormController">
<property name="validator"><ref bean="userValidator"/></property>
</bean>
The commandClass property is configure the model class with this request and controller. The code for the commandClass is:
<bean id="enternameController" class="net.roseindia.web.UserFormController">
<property name="commandClass"><value>net.roseindia.web.User</value></property>
</bean>
The commandName is the name of the command that is used to access data from the business layer and provided data to view layer for view. The code for the commandName property is:
<bean id="enternameController" class="net.roseindia.web.UserFormController">
<property name="commandName"><value>user</value></property>
</bean>
The successView property is used to display view after the process request for this request. The formView property provide view of the request.
Step 4:
Now we will create a entername.jsp file inside the WEB-INF/jsp/ folder for enter name by the user. The code of the entername.jsp is:
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="spring" uri="/spring"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>Enter Name</title>
</head>
<body>
<center>
<h1>Enter name</h1>
<br/>
<form:form commandName="user" method="POST" name="user">
Name:<form:input path="name"/><br/>
<font color="red"><form:errors path="name"/></font><br/>
<input type="submit" value="Save"/>
</form:form>
</center>
</body>
</html>
Step 5:
Now we will create a sayhello.jsp for display the name with "Hello". And after success the request of the name enter by the user. The code of the sayhello.jsp is:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<center>
<font size="16">
<c:out value="${prestatement}"/>
<c:out value=" "/>
<c:out value="${user.name}"/>
</font>
</center>
</body>
</html>
Step 6:
Now we will create a UserFormController.java class inside the application src folder that process the request and return the model data and formView for the application. The code of theUserFormController.java is:
packagenet.roseindia.web;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.ServletException;
importorg.springframework.web.servlet.ModelAndView;
importorg.springframework.web.servlet.view.RedirectView;
importorg.springframework.web.servlet.mvc.SimpleFormController;
importnet.roseindia.web.User;
@SuppressWarnings("deprecation")
publicclassUserFormControllerextendsSimpleFormController{
@Override
protectedModelAndView onSubmit(Object command)throwsServletException{
User user =(User) command;
String name = user.getName();
String prestatement ="Hello";
ModelAndView modelAndView =newModelAndView(getSuccessView());
modelAndView.addObject("user", user);
modelAndView.addObject("prestatement", prestatement);
returnmodelAndView;
}
}
Step 7:
Now we will create a UserValidator.java class for validate the entername.jsp file form fields. The code of the UserValidator.java is:
packagenet.roseindia.web;
importorg.springframework.validation.Errors;
importorg.springframework.validation.Validator;
importorg.springframework.validation.ValidationUtils;
importnet.roseindia.web.*;
publicclassUserValidatorimplementsValidator{
@Override
publicbooleansupports(Class clazz){
returnUser.class.isAssignableFrom(clazz);
}
publicvoidvalidate(Object obj,Errors errors){
User user =(User) obj;
if(user.getName()==null|| user.getName().length()==0){
errors.rejectValue("name","error.empty.field","Please Enter Name");
}
}
}
Step 8:
Now we will create a Model class inside the project src folder. that provide the business functionality in the application. The code of the User.java is:
package net.roseindia.web;
public class User {
public User(){}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Step 9:
Now we will run this application and see the output that have a hyperlink:
Now we will be click on this hyperlink that link with the entername.html file. So server send us on the entername.html file.
Now we will enter name and save and final output is:
Spring 2.5 MVC User Login Example
This section explains you how you can make Login example using Spring MVC module. In this login example we are not connecting to any database, but you can easily add the database access code to validate your user. In this example if user enters Username: admin and Password: admin, user get validates successfully and success page is displayed. If user enters something else error message is displayed. We have also validated the form data using the a custom validator class.Here we will create a user login web application that accept two values username and password entered by the User. If the username and password is correct then user successfully login otherwise application display errors for user.
Step 1:
Now we will create a index.jsp in project's WebContent folder. In the index.jsp file we will create a hyperlink "User Login Here" that will be linked "login.html" file. The code of the index.jsp is:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<title>Login Link Page</title>
</head>
<body bgcolor="#EEEEEE">
<center>
<a href="login.html">User Login Here</a><br/><br/>
</center>
</body>
</html>
Step 2:
Now we will configured the web.xml file for the DispatcherServlet. The code for web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>/spring</taglib-uri>
<taglib-location>/WEB-INF/spring.tld</taglib-location>
</taglib>
</web-app>
Step 3:
Now we will create dispatcher-servlet.xml inside the WEB-INF folder that will have all the configuration beans for handle the user requests. The code of the dispatcher-servlet.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:p="http://www.springframework.org/schema/p">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref local="localeChangeInterceptor"/>
</list>
</property>
<property name="urlMap">
<map>
<entry key="/login.html">
<ref bean="loginController"/>
</entry>
</map>
</property>
</bean>
<bean id="loginValidator" class="net.roseindia.web.LoginValidator"/>
<bean id="loginController" class="net.roseindia.web.LoginFormController">
<property name="sessionForm"><value>false</value></property>
<property name="commandName"><value>login</value></property>
<property name="commandClass"><value>net.roseindia.web.Login</value></property>
<property name="validator"><ref bean="loginValidator"/></property>
<property name="formView"><value>login</value></property>
<property name="successView"><value>success</value></property>
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="hl"/>
</bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>
</beans>
Step 4:
Now we will create two jsp files inside WEB-INF/jsp/ folder. First is login.jsp for taking input from the user and other is success.jsp for display the login success in this application. The login.jsp file will have two text fields (username and password) for take input by the users.
The code of the login.jsp is:
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="spring" uri="/spring"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head><title>Login</title></head>
<body>
<center>
<h3>Login page</h3>
<br/>
<form:form commandName="login" method="POST" name="login">
Username:<form:input path="username"/>
<font color="red"><form:errors path="username"/></font><br/><br/>
Password:<form:password path="password"/>
<font color="red"><form:errors path="password"/></font><br/><br/>
<input type="submit" value="Login"/>
</form:form>
</center>
</body>
</html>
Step 5:
The success.jsp file is contain code for display login success and contain the reverse link for users to come back on the login.html page. The code of the success.jsp is:
<%@ page session="false"%>
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="spring" uri="/spring" %>
<html>
<head>
<title>Success</title>
</head>
<body>
<center>
<h1>Welcome <core:out value="${name}"/></h1><br>
<a href="login.html">Back</a>
</center>
</body>
</html>
Step 6:
Now we will create a Login.java file inside the src folder that will have the business logic for the user login application. In this file we will declared two private variable username and password and create setter and getter method for username and password. The code of the Login.java is:
package net.roseindia.web;
public class Login {
public Login(){}
private String username;
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
We have configure this class in dispatcher-servlet..xml through commandName and commandClass. The code for the configuration in the dispatcher-servlet.xml is:
<bean id="loginController" class="net.roseindia.web.LoginFormController">
<property name="commandName"><value>login</value></property>
<property name="commandClass"><value>net.roseindia.web.Login</value></property>
</bean>
Step 7:
Now we will create a LoginFormController.java file that extends SimpleFormController for control the login request and return ModelAndView. we have configure this controller in dispatcher-servlet.xml by adding following properties:
<property name="urlMap">
<map>
<entry key="/login.html">
<ref bean="loginController"/>
</entry>
</map>
</property>
This code is include in the urlMap for mapping controller for a particular request and define controller by using bean properties adding following code:
<bean id="loginController" class="net.roseindia.web.LoginFormController">
</bean>
The LoginFormController.java code is:
package net.roseindia.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import net.roseindia.web.Login;
@SuppressWarnings("deprecation")
public class LoginFormController extends SimpleFormController {
@Override
protected ModelAndView onSubmit(Object command) throws ServletException {
Login login = (Login) command;
String name = login.getUsername();
String prestatement = "Hello";
ModelAndView modelAndView = new ModelAndView(getSuccessView());
modelAndView.addObject("name", name);
return modelAndView;
}
}
Step 8:
Now we will create a LoginValidator.java file in the project src directory for validate the login form. DispatcherServlet gives a property to add validator for a login request. The Code for dispatcher-servlet servlet.xml is:
<bean id="loginValidator" class="net.roseindia.web.LoginValidator"/>
<bean id="loginController" class="net.roseindia.web.LoginFormController">
<property name="validator"><ref bean="loginValidator"/></property>
</bean>
The LoginValidator.java file code is:
package net.roseindia.web;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.validation.ValidationUtils;
import net.roseindia.web.*;
public class LoginValidator implements Validator {
@Override
public boolean supports(Class clazz) {
return Login.class.isAssignableFrom(clazz);
}
public void validate(Object obj, Errors errors) {
Login login = (Login) obj;
if (login.getUsername() == null || login.getUsername().length() == 0) {
errors.rejectValue("username",
"error.empty.field", "Please Enter User Name");
}
else if (!login.getUsername().equals("admin")) {
errors.rejectValue("username", "unknown.user", "Unknown User");
}
if (login.getPassword() == null || login.getPassword().length() == 0) {
errors.rejectValue("password",
"error.empty.field", "Please Enter Password");
}
else if (!login.getPassword().equals("admin")) {
errors.rejectValue("password", "wrong.password", "Wrong Password");
}
}
}
Now we will run this login application and see the out put like:
Now click on this hyperlink the application display user login form like:
Now input "admin" as username and "admin" as password and test it. The result is:
Spring 2.5 MVC User Registration Example
This tutorial shows you how to create user registration application in Spring MVC. This application is not backed with the database. But you can easily modify the Controller class and add database capability and then save the user information into database. This is the next step towards learning Spring MVC. After completing this tutorial you will be able to develop form based applications in MVC. This tutorial will also show you how to validate the user input and display the errors messages on the screen.In this tutorial, we will create a user registration web application that accept the detail of the use, validate it and then get those values in Controller class. This application can be extends to add the database capability in the Controller class.
Step 1:
Now we will create a index.jsp in project's WebContent folder. In the index.jsp file we will create a hyperlink "New User Registration" that will be linked "registration.html" file. The code of the index.jspis:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<title>Registration Link Page</title>
</head>
<body bgcolor="#EEEEEE">
<center>
<a href="registration.html">New User Registration</a>
</center>
</body>
</html>
Step 2:
Now we will configured the web.xml file for the DispatcherServlet. The code for web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>/spring</taglib-uri>
<taglib-location>/WEB-INF/spring.tld</taglib-location>
</taglib>
</web-app>
Step 3:
Now we will create dispatcher-servlet.xml inside the WEB-INF folder that will have all the configuration beans for handle the user registration requests. We will set all the properties for the registration like validator, commandClass, commandName, session, formView, successView etc. You can see how to set these properties in the dispatcher-servlet.xml file. The code of the dispatcher-servlet.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:p="http://www.springframework.org/schema/p">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref local="localeChangeInterceptor"/>
</list>
</property>
<property name="urlMap">
<map>
<entry key="/registration.html">
<ref bean="registrationController"/>
</entry>
</map>
</property>
</bean>
<bean id="registrationValidator" class="net.roseindia.web.RegistrationValidator"/>
<bean id="registrationController" class="net.roseindia.web.RegistrationFormController">
<property name="sessionForm"><value>false</value></property>
<property name="commandName"><value>user</value></property>
<property name="commandClass"><value>net.roseindia.web.User</value></property>
<property name="validator"><ref bean="registrationValidator"/></property>
<property name="formView"><value>registration</value></property>
<property name="successView"><value>registrationsuccess</value></property>
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="hl"/>
</bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.Session
LocaleResolver"/>
</beans>
In the above code we have used the form validator with the help of code: <property name="validator"><ref bean="registrationValidator"/></property>
The registrationValidator bean id define in the configuration file using following code:
<bean id="registrationValidator" class="net.roseindia.web.RegistrationValidator"/>
In the net.roseindia.web.RegistrationValidator class we have defined the validation logic.
In this tutorial, dispatcher-servlet.xml provide us how to use viewResolver in the web application. we have added some code for viewResolver which enable you to render models in a browser without tying you to a specific view technology. The code is:
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
The dispatcher-servlet.xml also configure urlMapping for a particular request. We have include following code in dispatcher-servlet.xml file for the urlMapping and set the registrationController for the user registration request.
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref local="localeChangeInterceptor"/>
</list>
</property>
<property name="urlMap">
<map>
<entry key="/registration.html">
<ref bean="registrationController"/>
</entry>
</map>
</property>
</bean>
Step 4:
Now we will create registration.jsp inside /WEB-INF/jsp/ folder. In this file we will created user interface for enter registration information by the user. The code of the registration.jsp is:
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="spring" uri="/spring"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head><title>User Registration</title></head>
<body>
<center>
<h3>Registration page</h3>
<br/>
<form:form commandName="user" method="POST" name="user">
<table border="0">
<tr>
<td>Username:</td>
<td><form:input path="username"/></td>
<td><font color="red"><form:errors path="username"/></font></td>
</tr>
<tr>
<td>Password:</td>
<td><form:password path="password"/></td>
<td><font color="red"><form:errors path="password"/></font></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><form:password path="confirmpassword"/></td>
<td><font color="red"><form:errors path="confirmpassword"/></font></td>
</tr>
<tr>
<td>Email ID:</td>
<td><form:input path="emailid"/></td>
<td><font color="red"><form:errors path="emailid"/></font></td>
</tr>
<tr>
<td>Address:</td>
<td><form:input path="address"/></td>
<td><font color="red"><form:errors path="address"/></font></td>
</tr>
<tr>
<td colspan="3" align="center"><input type="submit" value="Save"/></td>
</tr>
</table>
</form:form>
</center>
</body>
</html>
Step 5:
Now we will create a registrationsuccess.jsp that will display when request process successfully then request controller send response for the user. The registration.jsp display all information of the user that will registered currently. The code of the registration.jsp is:
<%@ page session="false"%>
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="spring" uri="/spring" %>
<html>
<head>
<title>Success</title>
</head>
<body>
<center>
<h3>User Registered Successfully.</h3><br>
<table>
<tr>
<td colspan="2" align="center"><font size="5">User Information</font></td>
</tr>
<tr>
<td>Username:</td>
<td><core:out value="${user.username}"/></td>
</tr>
<tr>
<td>Email ID:</td>
<td><core:out value="${user.emailid}"/></td>
</tr>
<tr>
<td>Address:</td>
<td><core:out value="${user.address}"/></td>
</tr>
</table>
<a href="registration.html">Back</a>
</center>
</body>
</html>
Step 6:
Now we will created business class in the project src folder for user registration that's name User.java that will have user information related private variable and setter, getter methods for access of these variables. This class is a command class for the user registration request. The code for the User.javais:
package net.roseindia.web;
public class User {
public User(){
AbstractController example in Spring web MVC framework
In this tutorial we are discussing AbstractContoller. The AbstractController class is extended by the programmer's to create the controller for their application.Abstract controller provides a basic infrastructure, all of Spring's Controllers are inherited from AbstractController. The AbstractController is a class that offers caching support. You can extend AbstractController class and then implement your own controller from scratch. It should be used for simple use like returning a resource to the client without checking request parameters.
Here we will create a Spring 2.5 MVC web application that will be used AbstractController for creating the controller for the application.
Step 1:
Now we will create index.jsp inside the application WebContent folder. In the index.jsp, we will create a hyperlink for send request and controlled by the AbstractController. If user click on "Show Message" link then a message is appear on the user browser. The code of the index.jsp is:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<body>
<a href="abstractcontroller.html">Show Message</a>
</body>
</html>
Step 2:
Now we will configured the web.xml file for DispatcherServlet. The code of the web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd" >
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Step 3:
Now we will create a dispatcher-servlet.xml in the WEB-INF folder. We will be create bean setting for the all requests in this file.
We will be create a viewResolver that resolve all the .html request in to .jsp. The code of the dispatcher-servlet.xml for viewResolver is:
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="localeResolver"class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>
we will create a bean for urlMapping that mapped the request for a particular controller. In this example we will create urlMapping for abstractcontroller.html to abstractcontroller. The code of the urlMapping in the dispatcher-servlet.xml is:
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref local="localeChangeInterceptor"/>
</list>
</property>
<property name="urlMap">
<map>
<entry key="/abstractcontroller.html">
<ref bean="abstractController"/>
</entry>
</map>
</property>
</bean>
<bean id="localeChangeInterceptor"class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="hl"/>
</bean>
Now the full code of the dispatcher-servlet.xml for the AbstractController is:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org
/schema/beans/spring-beans-2.5.xsd"
xmlns:p="http://www.springframework.org/schema/p">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref local="localeChangeInterceptor"/>
</list>
</property>
<property name="urlMap">
<map>
<entry key="/abstractcontroller.html">
<ref bean="abstractController"/>
</entry>
</map>
</property>
</bean>
<bean id="abstractController" class="net.roseindia.web.ABSController"></bean>
<bean id="localeChangeInterceptor" class=
"org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="hl"/>
</bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>
</beans>
Step 4:
Now we will create a abscontroller.jsp inside the WEB-INF/jsp/ folder. This is the success page for display the message send by the ABSController.java. The code of the abscontroller.jsp is:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<c:out value="${message}"/>
</body>
</html>
Step 5:
Now we will create a ABSController.java class file inside the project src folder that extends AbstractController. This class controlled the request that have mapped for the particular request. This class accept the request and return the ModelAndView for display on the user browser. The code of theABSController.java is:
package net.roseindia.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class ABSController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String Mess = "Abstract Controller Test";
ModelAndView modelAndView = new ModelAndView("abscontroller");
modelAndView.addObject("message", Mess);
return modelAndView;
}
}
Step 6:
When you run this application it will display output as shown below:
after click on the "Show Message" link that connect this link with "abstractcontroller.html" and the message like:
Controller Interface implementation example in Spring 2.5 Web MVC framework:-
In this section we will see the example of Controller Interface in Spring MVC.
The Base portlet Controller interface (org.springframework.web.servlet.mvc.Controller) is a components that receives RenderRequest/RenderResponse and also the ActionRequest/ActionResponse in the same was as a Portlet. The difference is that it also participate in an MVC workflow.
The implementation of org.springframework.web.servlet.mvc.Controller is reusable and threadsafe. The implementation class is also capable of handling multiple.
In this tutorial we have created our controller by extending org.springframework.web.servlet.mvc.Controller interface. Here we will create a Spring 2.5 Web MVC example that used Controller Interface for control the user request.
Step 1:
Now we will create a index.jsp in project WebContent folder that contains a hyperlink "Controller" that linked "controllerinterface.html". When user click on this link a request will generate. The code of theindex.jsp is:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<body>
<a href="controllerinterface.html">controller</a>
</body>
</html>
Step 2:
Now we will modify the web.xml for set the DispatcherServlet for this application and set the welcome file. The code of the web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd" >
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Step 3:
Now we will create a dispatcher-servlet.xml file inside the project WEB-INF folder. The dispatcher-servlet.xml have the bean setting for viewResolver, urlMapping for assign the controller for the particular request. The code of the dispatcher-servlet.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:p="http://www.springframework.org/schema/p">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref local="localeChangeInterceptor"/>
</list>
</property>
<property name="urlMap">
<map>
<entry key="/controllerinterface.html">
<ref bean="requestController"/>
</entry>
</map>
</property>
</bean>
<bean id="requestController" class=
"net.roseindia.web.RequestControllerInterface"></bean>
<bean id="localeChangeInterceptor" class=
"org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="hl"/>
</bean>
<bean id="localeResolver" class=
"org.springframework.web.servlet.i18n.SessionLocaleResolver"/>
</beans>
Step 4:
Now we will create a RequestControllerInterface.java file inside of the project src folder. In this class we will implements "Controller" Interface for control the user request and return the ModelAndView as response. The application display that response for the user interface. The code of theRequestControllerInterface.java is:
packagenet.roseindia.web;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.springframework.web.servlet.ModelAndView;
importorg.springframework.web.servlet.mvc.Controller;
publicclassRequestControllerInterfaceimplementsController{
publicModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response)throwsException{
ModelAndView modelandview =newModelAndView("controllerinterface");
modelandview.addObject("message","This is example of Controller Interface");
returnmodelandview;
}
}
Step 5:
Now we will create a controllerinterface.jsp file inside the /WEB-INF/jsp/ folder. This jsp file contain code to display the response that will return by the controller. The code of the controllerinterface.jsp is:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<c:out value="${message}"/>
</body>
</html>
Step 6:
Now we will run this application and see the output like:
After click on this link request controller provide us message as a View like:
Download Code
ParameterizableViewController example
ParameterizableViewController example in Spring 2.5 Web MVC framework.
This controller is use to redirect the page in the Spring 2.5 Web MVC applications. This controller doesn't require controller class. This controller provides an alternative to sending a request straight to a view such as a JSP. we will configure just declared the ParameterizableViewController bean and set the view name through the "viewName" property.Now we will used ParameterizedViewController for control the behavior of the application.
Step 1:
Now we will create a index.jsp that will have a hyperlink that linked with the parameterizableviewcontroller.html. If user click on this link the request will generate for the parameterizableviewcontroller.html. The code of the index.html is:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<a href="parameterizableviewcontroller.html">ParameterizableViewController Example</a>
Step 2:
Now we will configure the DispatcherServlet in the web.xml. The DispatcherServlet will be configure to process all the request that have ending with .html. In this web.xml we will also define how to use spring.tld for the Spring 2.5 Web MVC application. Here is the code of the web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3
//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>/spring</taglib-uri>
<taglib-location>/WEB-INF/spring.tld</taglib-location>
</taglib>
</web-app>
Step 3:
Now we will create a xml file inside the project WEB-INF folder with dispatcher-servlet.xml name. This is the main configuration file for the Spring web application. In this file all request will configure with the particular controller by beans setting and urlMapping defined in it. The code of the dispatcher-servlet.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<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 class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/parameterizableviewcontroller.html">parameterizableController</prop>
</props>
</property>
</bean>
<bean name="parameterizableController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController">
<property name="viewName" value="ParameterizableController" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
If the parameterizableviewcontroller.html request will occurred then dispatcher-servlet.xml will provide the controller for control this request that's name parameterizableController. But parameterizableController is derived by ParameterizableViewController that redirect the page by using viewName property.
Step 4:
Now we will create ParameterizableController.jsp page that is display as a user interface after redirect page by the ParameterizableViewController. The code of the ParameterizableController.jsp is:
<html>
<body>
<h4>ParameterizableViewController Example.<br/> No controller class required for
this controller</h4>
</body>
</html>
Step 5:
Now we will run this application and see the output like:
Now click on this link and see, the application will display like:
Download Code
MultiActionController example in
MultiActionController example in Spring 2.5 Web MVC
In this section we will learn about the MultiActionController class of Spring MVC. We will also show you the example to use this class. You can download MultiActionController example and run in Eclipse IDE or reconfigure the code in IDE of your choice.Example of MultiActionController Class
MultiActionController class provides us a functionality that allow to bind the multiple request-handling methods in a single controller. The MultiActionController used MethodNameResolver or ParameterMethodNameResolver to find which method to be call when handling an incoming request. In this example we will discuss about how to use MultiActionController.
Step 1:
Now we will create a index.jsp that will have four hyperlinks to generates difference types of requests. The code of the index.jsp is:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<title>Multi Action Controller Example</title>
</head>
<body>
<h4>Multi Action Controller Example</h4>
<a href="add.html" >Add</a> <br/>
<a href="update.html" >Update</a><br/>
<a href="edit.html" >Edit</a> <br/>
<a href="remove.html" >Remove</a>
</body>
</html>
Step 2:
Now we will configure the web.xml for DispatcherServlet. The code of the web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http:
//java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Step 3:
Now we will create a dispatcher-servlet.xml inside the /WEB-INF/ folder. The dispatcher-servlet.xml have the viewResolver that's provide a way to address views which enable you to render models in a browser without tying you to a specific view technology. The dispatcher-servlet.xml will have bean setting for provide the controller of these requests. The code for configure the MultiActionController in the dispatcher-servlet.xml is:
<bean name="/*.html" class="net.roseindia.web.MultiActionControllerExample" />
The full code of the dispatcher-servlet.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:p="http://www.springframework.org/schema/p">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean name="/*.html" class="net.roseindia.web.MultiActionControllerExample" />
</beans>
Step 4:
Now we will create a showmessage.jsp in the /WEB-INF/jsp/ folder. It will be display the response(that's return by the controller class) for the user. The code of the showmessage.jsp is:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Success Page</title>
</head>
<body>
${message}
</body>
</html>
Step 5:
Now we will create a MultiActionControllerExample.java class inside the project src folder that extends the MultiActionController class. We will import "org.springframework.web.servlet.mvc.multiaction.MultiActionController" for extends MultiActionController class in MultiActionControllerExample.java. The MultiActionControllerExample.java class will have four methods for handle the user requests. The code of theMultiActionControllerExample.java is:
packagenet.roseindia.web;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.springframework.web.servlet.ModelAndView;
importorg.springframework.web.servlet.mvc.multiaction.MultiActionController;
publicclassMultiActionControllerExampleextendsMultiActionController{
publicModelAndView add(HttpServletRequest request,
HttpServletResponse response)throwsException{
returnnewModelAndView("showmessage","message","Add method called");
}
publicModelAndView update(HttpServletRequest request,
HttpServletResponse response)throwsException{
returnnewModelAndView("showmessage","message","Update method called");
}
publicModelAndView edit(HttpServletRequest request,
HttpServletResponse response)throwsException{
returnnewModelAndView("showmessage","message","Edit method called");
}
publicModelAndView remove(HttpServletRequest request,
HttpServletResponse response)throwsException{
returnnewModelAndView("showmessage","message","Remove method called");
}
}
Step 6:
Now we will run this project and see the output like:
User can see four hyperlink in this page. User click on these links and see output like:
Click on Add link:
Click on Update link:
Click on Edit link:
Click on Remove link:
Download Code
UrlFileNameViewController Example
UrlFileNameViewController Example in Spring 2.5 Web MVC Framework
If user don't want to include any logical operation on request and redirect to some resource then user used UrlFilenameViewController that's transform the virtual path of a URL into a view name and provide a view to display as a user interface. In this example we will discuss about UrlFileNameViewController.Let's start developing the example program that uses UrlFileNameViewController class. Follow the steps mentioned below and develop the example program. You can also download source code of UrlFileNameViewController example discussed here from the download link provided at the end of this tutorial.
Step 1:
Now we will create index.jsp file inside the project WebContent folder that'll have two hyperlink to send user requests for "MyAddress.html" and "MyOfficeAddress.html". After that we will set this file as a welcome file in the web.xml configuration file. The code of the index.jsp is:
<html>
<head></head>
<body>
<h3>UrlFileNameViewController Example</h3>
<h4><a href="MyAddress.html">My Home Address</a></h4><br/>
<h4><a href="MyOfficeAddress.html">My Office Address</a></h4>
</body>
</html>
Step 2:
Now we will configured the web.xml file for the DispatcherServlet and will have welcome file setting. The code of the web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http:
//java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Step 3:
Now we will create a dispatcher-servlet.xml file inside the /WEB-INF/ folder that will have all configuration beans for the each and every request and set controllers for each request. we will create a bean for the UrlFileNameViewController for provide the control the requests. The code for use UrlFileNameViewController in the dispatcher-servlet.xml is:
<bean id="staticViewController"class="org.springframework.web.servlet.mvc.UrlFilenameViewController"/>
Now we will set the viewResolver that will resolved the suffix and prefix for the response. The code for viewResolver in the dispatcher-servlet.xml is:
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
Now we will used UrlFolenameViewController with the urlMapping. The code of the urlMapping with UrlFolenameViewController in dispatcher-servlet.xml is:
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref local="localeChangeInterceptor"/>
</list>
</property>
<property name="urlMap">
<map>
<entry key="/*.html">
<ref bean="staticViewController"/>
</entry>
</map>
</property>
</bean>
The full code of the dispatcher-servlet.xml for the UrlFileNameViewController is:
<?xml version="1.0" encoding="UTF-8"?>
<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="staticViewController"
class="org.springframework.web.servlet.mvc.UrlFilenameViewController"/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref local="localeChangeInterceptor"/>
</list>
</property>
<property name="urlMap">
<map>
<entry key="/*.html">
<ref bean="staticViewController"/>
</entry>
</map>
</property>
</bean>
<bean id="localeChangeInterceptor" class=
"org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="hl"/>
</bean>
</beans>
Step 4:
Now we will create two jsp file inside /WEB-INF/ folder that's name "MyAddress.jsp" and "MyOfficeAddress.jsp" for redirect the user on.
The code of the MyAddress.jsp is:
<html>
<head>
</head>
<body>
<h2>My Home Address</h2>
<h3> New Delhi </h3>
</body>
</html>
The code of the MyOfficeAddress.jsp is:
<html>
<head>
</head>
<body>
<h2>My Office Address</h2>
<h3>New Delhi</h3>
</body>
</html>
Now we will run this application and see the output like:
If user click on "My Home Address" link then output is:
If user click on "My Office Address" link then output is:
Download Code
Download this code
AbstractWizardFormCOntroller Example
AbstractWizardFormCOntroller Example Part1.
AbstractWizardFormController example in Spring 2.5 Web MVC
Spring Web MVC provides AbstractWizardFormController class that handle wizard form. In this tutorial, we will used AbstractWizardFormController class. The AbstractWizardFormController class provide us to store and show the forms data with multiple pages. It manage the navigation between pages and validate the user input data form a single page of the whole model object at once. In this tutorial we will discuss about this controller.Step 1:
Now we will create a index.jsp inside the WebContent folder. It will have a hyperlink "AbstractWizardFormController Test Application". If user click on this link request will generate. The code of the index.jsp is:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<title>AbstractWizardFormController Example</title>
</head>
<body>
<center>
<a href="user1.html">
AbstractWizardFormController Test Application</a><br/>
</center>
</body>
</html>
Step 2:
Now we will configured web.xml for DispatcherServlet and spring.tld. The code of the web.xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns=
"http://java.sun.com/xml/ns/j2ee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd" version="2.5">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>/spring</taglib-uri>
<taglib-location>/WEB-INF/spring.tld</taglib-location>
</taglib>
</web-app>
Step 3:
Now we will create dispatcher-servlet.xml file in the /WEB-INF/ folder. The dispatcher-servlet.xml file contain urlMapping, viewResolver for the all requests. we will configure the AWizardFormController for this application. User can see the code tin the dispatcher-servlet.xml file. the full code of thedispatcher-servlet.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:p="http://www.springframework.org/schema/p">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref local="localeChangeInterceptor"/>
</list>
</property>
<property name="urlMap">
<map>
<entry key="/user1.html">
<ref bean="wizardController"/>
</entry>
</map>
</property>
</bean>
<bean id="wizardController" class="net.roseindia.web.AWizardFormController">
<property name="commandName"><value>user</value></property>
<property name="commandClass"><value>net.roseindia.web.User</value></property>
<property name="pages"><value>user1,user2,user3</value></property>
<property name="pageAttribute"><value>page</value></property>
</bean>
<bean id="localeChangeInterceptor" class=
"org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="hl"/>
</bean>
<bean id="localeResolver" class=
"org.springframework.web.servlet.i18n.SessionLocaleResolver"/> </beans>
AbstractWizardFormCOntroller Example Part2.
SimpleFormController Example in Spring 2.5 Web MVC Framework
Spring provides SimpleFromController for control a form data in the web application. If you want to handle form in spring then you need to use SimpleFormController by extending these in your Controller class. It's provides formView, successView in the case of valid submission and provide validation errors if wrong data entry by the user in the form data. This is also handle model object for binding and fetching data. In this example we will discuss about SimpleFormController work flow. In this example we will create a form that accept user data and display.Step 1:
Now we will create a index.jsp inside the WebContent folder that will have a hyperlink "Fill User Personal Details "for generate user request to enter user detail. The code of the index.jsp is:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<title>User Welcome Page</title>
</head>
<body bgcolor="#EEEEEE">
<center>
<a href="user.html">Fill User Personal Details</a>
</center>
</body>
</html>
Step 2:
Now we will configured web.xml for DispatcherServlet and spring.tld. The code of the web.xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd" version="2.5">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>/spring</taglib-uri>
<taglib-location>/WEB-INF/spring.tld</taglib-location>
</taglib>
</web-app>
Step 3:
Now we will create a dispatcher-servlet.xml file inside the project /WEB-INF/ folder. The dispatcher-servlet.xml file will have configuration code for the particular request and configure a controller that request with set some properties like formView, succesView, commandClass, CommandName, validator etc. The code of the dispatcher-servlet.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:p="http://www.springframework.org/schema/p">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref local="localeChangeInterceptor"/>
</list>
</property>
<property name="urlMap">
<map>
<entry key="/user.html">
<ref bean="userController"/>
</entry>
</map>
</property>
</bean>
<bean id="userValidator" class="net.roseindia.web.UserValidator"/>
<bean id="userController" class="net.roseindia.web.UserFormController">
<property name="sessionForm"><value>false</value></property>
<property name="commandName"><value>user</value></property>
<property name="commandClass"><value>net.roseindia.web.User</value></property>
<property name="validator"><ref bean="userValidator"/></property>
<property name="formView"><value>user</value></property>
<property name="successView"><value>usersuccess</value></property>
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="hl"/>
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>
</beans>
In this dispatcher-servlet.xml we have also declared beans for urlMapping and viewResolver.
Step 4:
Now we will create two jsp files user.jsp and usersuccess.jsp inside the /WEB-INF/jsp/ folder. The user.jsp contain a form and form fields for user interface. The code of the user.jsp is:
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="spring" uri="/spring"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head><title>User Personal Details</title></head>
<body>
<center> <h3>User Personal Details</h3>
<br/>
<form:form commandName="user" method="POST" name="user">
<table border="0">
<tr>
<td>Name:</td>
<td><form:input path="name"/></td>
<td><font color="red"><form:errors path="name"/></font></td>
</tr>
<tr>
<td>Email ID:</td>
<td><form:input path="emailid"/></td>
<td><font color="red"><form:errors path="emailid"/></font></td>
</tr>
<tr>
<td>Date of birth:</td>
<td><form:input path="dob"/></td>
<td><font color="red"><form:errors path="dob"/></font></td>
</tr>
<tr>
<td>Qualification:</td>
<td><form:input path="qualification"/></td>
<td><font color="red"><form:errors path="qualification"/></font></td></tr>
<tr>
<td>Contact Number:</td>
<td><form:input path="contact"/></td>
<td><font color="red"><form:errors path="contact"/></font></td>
</tr>
<tr>
<td>Address:</td>
<td><form:input path="address"/></td>
<td><font color="red"><form:errors path="address"/></font></td>
</tr>
<tr>
<td colspan="3" align="center"><input type="submit" value="Save"/></td>
</tr>
</table>
</form:form>
</center>
</body>
</html>
The usersuccess.jsp file display data entered by the user in the user.jsp form. The code of theusersuccess.jsp is:
<%@ page session="false"%>
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="spring" uri="/spring" %>
<html>
<head>
<title>User Personal Details Display</title>
</head>
<body>
<center>
<h3>User Personal Details Display</h3><br>
<table>
<tr>
<td colspan="2" align="center"><font size="5">User Information</font></td>
</tr>
<tr>
<td>Name:</td>
<td><core:out value="${user.name}"/></td>
</tr>
<tr>
<td>Email ID:</td>
<td><core:out value="${user.emailid}"/></td>
</tr>
<tr>
<td>Date Of Birth:</td>
<td><core:out value="${user.dob}"/></td>
</tr>
<tr>
<td>Qualification:</td>
<td><core:out value="${user.qualification}"/></td>
</tr>
<tr>
<td>Contact Number:</td>
<td><core:out value="${user.contact}"/></td>
</tr>
<tr>
<td>Address:</td>
<td><core:out value="${user.address}"/></td>
</tr>
</table>
<a href="user.html">Back</a>
</center>
</body>
</html>
Step 5:
Now we will create User.java class inside the project src folder that will have some variables and setter and getter for these variables. we have used this class instance as a commandName and use this class as a command class for request controller. The code of the User.java class is:
package net.roseindia.web;
public class User {
public User(){}
private String name;
private String emailid;
private String dob;
private String address;
private String qualification;
private String contact;
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getQualification() {
return qualification;
}
public void setQualification(String qualification) {
this.qualification = qualification;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmailid() {
return emailid;
}
public void setEmailid(String emailid) {
this.emailid = emailid;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Step 6:
Now we will create UserFormController.java class that extends SimpleFormController inside the project src folder for control the request. It will have override onSubmit() method that accept class object as a parameter and after proceed these object return ModelAndView for the user display. The code of theUserFormController.java class is:
package net.roseindia.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import net.roseindia.web.User;
@SuppressWarnings("deprecation")
public class UserFormController extends SimpleFormController {
@Override
protected ModelAndView onSubmit(Object command)
throws ServletException {
User user = (User) command;
ModelAndView modelAndView = new ModelAndView(getSuccessView());
modelAndView.addObject("user", user);
return modelAndView;
}
}
wresolver
InternalResourceViewResolver Example
InternalResourceViewResolver example in Spring 2.5 MVC
In this tutorial we are discussing about InternalResourceViewResolver class, which is one of the several view resolvers in Spring 2.5.Spring 2.5 have two most important way for handles views. First is ViewResolver that provides mapping between view names and real views. Second is View interface that provides the view for the requests. In this tutorial we will discuss about InternalResourceViewResolver that support Servlet, JSP and subclasses like JstlView and TilesView.
Step 1:
We will create a index.jsp file inside the WebContent folder. The index.jsp will have a link that generate user request. The code of the index.jsp is:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<title>Internal Resource View Resolver</title>
</head>
<body>
<center>
<a href="viewresolver.html">Internal Resource View Resolver</a>
</center>
</body>
</html>
Step 2:
Now we will configure the web.xml file for DispatcherServlet. The code of the web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>/spring</taglib-uri>
<taglib-location>/WEB-INF/spring.tld</taglib-location>
</taglib>
</web-app>
Step 3:
Now we will create a dispatcher-servlet.xml file inside the /WEB-INF/ folder. The dispatcher-servlet.xml file will contain code for the urlMapping and viewResolver. The code for include InternalResourceViewResolver as a resolver like:
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean
Spring MVC controllers are always return ModelAndView after that InternalResourceViewResolver resolver that and add prefix and suffix and provide the view for the particular request. The full code of the dispatcher-servlet.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<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 class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/viewresolver.html">viewResolverController</prop>
</props>
</property>
</bean>
<bean name="viewResolverController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController">
<property name="viewName" value="message" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
Step 4:
Now we will create a message.jsp file inside the /WEB-INF/jsp/ folder that display a message for the user as response. The code of the message.jsp is:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Internal Resource View Resolver Example</title>
</head>
<body>
<center>
<table>
<tr>
<td>
<b>This is Internal Resource View Resolver Example.</b>
</td>
</tr>
</table>
</center>
</body>
</html>
Step 5:
Now we will run this example and see the output like:
And after click on this link, the output like:
ResourceBundleViewResolver example in Spring 2.5 MVC
Learn how to use ResourceBundleViewResolver in Spring 2.5 MVC.The ResourceBundleViewResolver implements ViewResolver interface and uses the bean definitions in the properties files. In this example we will discuss how to used ResourceBundleViewResolver and how to create a properties files for the ResourceBundleViewResolve.
Step 1:
Now we will create a index.jsp that have a hyperlink for user click. The code of the index.jsp is:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<title>Resource Bundle View Resolver</title>
</head>
<body>
<center>
<a href="resourcebundle.html">Resource Bundle View Resolver</a>
</center>
</body>
</html>
Step 2:
Now we will customize the the web.xml file for the DispatcherServlet. The code of the web.xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>/spring</taglib-uri>
<taglib-location>/WEB-INF/spring.tld</taglib-location>
</taglib>
</web-app>
Step 3:
Now we will create a dispatcher-servlet.xml file in the /WEB-INF/ folder that is the main configuration file for this project. The dispatcher-servlet.xml file contain configuration code for the ResourceBundleViewResolver like:
<bean id="viewResolver"
class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename">
<value>spring-views</value>
</property>
</bean>
In this code, we have create a bean for ResourceBundleViewResolver and set id for this bean. This bean property that's name basename and have value spring-views this is the name of the properties file name. The properties file contain the class and url properties. The code of the spring-views.properties file is
resourcebundle.(class)=org.springframework.web.servlet.view.JstlView
resourcebundle.url=/WEB-INF/jsp/resourcebundle.jsp
The full code of the dispatcher-servlet.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:p="http://www.springframework.org/schema/p">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename">
<value>spring-views</value>
</property>
</bean>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref local="localeChangeInterceptor"/>
</list>
</property>
<property name="urlMap">
<map>
<entry key="/resourcebundle.html">
<ref bean="resourcebundleController"/>
</entry>
</map>
</property>
</bean>
<bean id="resourcebundleController" class="net.roseindia.web.ResourceBundleController">
</bean>
<bean id="localeChangeInterceptor"class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="hl"/>
</bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>
</beans>
Step 4:
Now we will create a resourcebundle.jsp in the /WEB-INF/jsp/ folder. This file display message for the user for successfully used ResourceBundleViewResolver. The code of the resourcebundle.jsp is:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Resource Bundle View Resolver Example</title>
</head>
<body>
<center>
<table>
<tr>
<td>
<b>This is Resource Bundle View Resolver Example.</b>
</td>
</tr>
</table>
</center>
</body>
</html>
Step 5:
Now we will create ResouceBundleController.java class in the project src folder to control the user request and implement AbstractController and return the ModelAndView. The code for theResouceBundleController.java is:
packagenet.roseindia.web;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.springframework.web.servlet.ModelAndView;
importorg.springframework.web.servlet.mvc.AbstractController;
publicclassResourceBundleControllerextendsAbstractController{
@Override
protectedModelAndView handleRequestInternal(HttpServletRequest request,HttpServletResponse response)throwsException{
StringMess="Resource Bumdle Example With Controller";
System.out.println("------>"+Mess);
ModelAndView modelAndView =newModelAndView("resourcebundle");
returnmodelAndView;
}
}
Step 6:
Now we will run this application and see the output like:
Now click on this link and see like:
Download code
Download this example code
XmlViewResolver Example in Spring 2.5 MVC
Example of XmlViewResolver in Spring 2.5 MVC.The XmlViewResolver offers us some basic functionality to retrieve views from a BeanFactory. The XmlViewResolver implements ViewResolver interface that uses XML file to define the bean definations and specified by resource location. The project contain this file inside the WEB-INF directory, the default name of the XML file is views.xml. The XmlViewResolver are not support Locale so if you want to usedlocal in your project then use XmlViewResolver. In this example, we will discuss about how to use XmlViewResolver.
Step 1:
Now we will create a index.jsp file that will have a link to generate user request. The code of theindex.jsp is:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<title>XML View Resolver</title>
</head>
<body>
<center>
<a href="xmlviewresolver.html">XML View Resolver</a>
</center>
</body>
</html>
Step 2:
Now we will customize the the web.xml file for the DispatcherServlet and set index.jsp as a welcome file . The code of the web.xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>/spring</taglib-uri>
<taglib-location>/WEB-INF/spring.tld</taglib-location>
</taglib>
</web-app>
Step 3:
Now we will create dispatcher-servlet.xml file inside the /WEB-INF/ directory that will have configuration code for the project. We will also configure the code for XmlViewResolver in this file. The code is:
<bean id="viewResolver" class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="location">
<value>/WEB-INF/spring-views.xml</value>
</property>
</bean>
In this code we have set bean id as "viewResolver" and set the class for this bean that indicate, the "XmlViewResolver" are used here. We have set the location property for this bean and provide value for this property as "/WEB/spring-views.xml". The spring-views.xml file is that file which is contain the actual view name. The code of the spring-views.xml file for this project is:
<?xml version="1.0" encoding="UTF-8"?>
<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="xmlviewresolver"
class="org.springframework.web.servlet.view.JstlView">
<property name="url" value="/WEB-INF/jsp/xmlviewresolver.jsp" />
</bean>
</beans>
The url property is provide the actual actual view for the particular response. The full code of thedispatcher-servlet.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:p="http://www.springframework.org/schema/p">
<bean id="viewResolver" class=
"org.springframework.web.servlet.view.XmlViewResolver">
<property name="location">
<value>/WEB-INF/spring-views.xml</value>
</property>
</bean>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref local="localeChangeInterceptor"/>
</list>
</property>
<property name="urlMap">
<map>
<entry key="/xmlviewresolver.html">
<ref bean="xmlviewresolverController"/>
</entry>
</map>
</property>
</bean>
<bean id="xmlviewresolverController" class=
"net.roseindia.web.XmlViewResolverController">
</bean>
<bean id="localeChangeInterceptor" class=
"org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="hl"/>
</bean>
<bean id="localeResolver" class=
"org.springframework.web.servlet.i18n.SessionLocaleResolver"/>
</beans>
Step 4:
Now we will create xmlviewresolver.jsp file inside the /WEB-INF/jsp/ folder. This file display as response when call by the viewResolver. The code of the xmlviewresolver.jsp is:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>XML View Resolver Example</title>
</head>
<body>
<center>
<table>
<tr>
<td>
<b>This is XML View Resolver Example.</b>
</td>
</tr>
</table>
</center>
</body>
</html>
Step 5:
Now we will create a controller class to control the user request and return ModelAndView as the response. In this class we will implements the AbstractController. We will create this class inside the src folder and the code of the XmlViewResolverController.java is:
packagenet.roseindia.web;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.springframework.web.servlet.ModelAndView;
importorg.springframework.web.servlet.mvc.AbstractController;
publicclassXmlViewResolverControllerextendsAbstractController{
@Override
protectedModelAndView handleRequestInternal(HttpServletRequest request,HttpServletResponse response)throwsException{
StringMess="XmlViewResolver Example";
System.out.println("------>"+Mess);
ModelAndView modelAndView =newModelAndView("xmlviewresolver");
returnmodelAndView;
}
}
Step 6:
Now we will run this application and see the output like:
After click on this link we will see like:
Download code
Download this example code
Chaining ViewResolvers example in Spring 2.5 MVC
Spring provides functioning that supports more then view resolvers in the application. If user want to use more then one view resolver in the application, it can be used Chaining view resolvers. The Chaining view resolver is a technique that implements more then one view resolvers to your application context and set the order property to set order for the view resolver. In this example we will used two view resolvers first is XmlViewResolver and second is InternalResourceViewResolver. The main task of the chaining view resolvers to use more then one view resolvers in the application.Step 1:
Now we will create a index.jsp that will have two links that generate the user requests. The code of theindex,jsp is:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<title>Chaining of View Resolvers</title>
</head>
<body>
<center>
<a href="internalresourceviewresolver.html">
Internal Resource ViewResolver</a><br/>
<a href="xmlviewresolver.html">XML View Resolver</a>
</center>
</body>
</html>
Step 2:
Now we will configured the web.xml for DispatcherServlet and set index.jsp as welcome file. We will also used spring tags library by setting in the web.xml. The code of the web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>/spring</taglib-uri>
<taglib-location>/WEB-INF/spring.tld</taglib-location>
</taglib>
</web-app>
Step 3:
Now we will create dispatcher-servlet.xml file inside the /WEB-INF/ folder that will have all configuration code for the application. We will create two view Resolvers in this xml file, first for InternalResourceViewresolver and second for XmlViewResolver. The code forInternalResourceViewResolver in the dispatcher-servlet.xml is:
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="order" value="0"/>
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
And the code for the XmlViewresolver in the dispatcher-servlet.xml is:
<bean id="viewResolver" class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="order" value="1"/>
<property name="location">
<value>/WEB-INF/spring-views.xml</value>
</property>
</bean>
The XmlViewResolver required a xml file that have bean definitions for the view so we will create a spring-views.xml file inside the /WEB-INF/ folder and set the location of this file in the XmlViewResolver configuration code. The code of the spring-views.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<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="xmlviewresolver"
class="org.springframework.web.servlet.view.JstlView">
<property name="url" value="/WEB-INF/jsp/xmlviewresolver.jsp" />
</bean>
</beans>
The spring-views.xml file provide the actual view for the particular request. The full code of thedispatcher-servlet.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:p="http://www.springframework.org/schema/p">
<bean id="viewResolver" class=
"org.springframework.web.servlet.view.XmlViewResolver">
<property name="order" value="1"/>
<property name="location">
<value>/WEB-INF/spring-views.xml</value>
</property>
</bean>
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="order" value="0"/>
<property name="viewClass" value=
"org.springframework.web.servlet.view.JstlView"/>
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref local="localeChangeInterceptor"/>
</list>
</property>
<property name="urlMap">
<map>
<entry key="/xmlviewresolver.html">
<ref bean="xmlviewresolverController"/>
</entry>
<entry key="/internalresourceviewresolver.html">
<ref bean="internalResourceViewResolverController"/>
</entry>
</map>
</property>
</bean>
<bean id="xmlviewresolverController" class=
"net.roseindia.web.XmlViewResolverController">
</bean>
<bean name="internalResourceViewResolverController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController">
<property name="viewName" value="message" />
</bean>
<bean id="localeChangeInterceptor" class=
"org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="hl"/>
</bean>
<bean id="localeResolver" class=
"org.springframework.web.servlet.i18n.SessionLocaleResolver"/>
</beans>
In this code we will used two view resolvers for the different view.
Step 4:
Now we will create a message.jsp inside the /WEB-INF/jsp/ folder that provide view for the InternalResourceViewResolver. The code of the message.jsp is:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content=
"text/html; charset=ISO-8859-1">
<title>Internal Resource View Resolver Example</title>
</head>
<body>
<center>
<table>
<tr>
<td>
<b>This is Internal Resource View Resolver Example.</b>
</td>
</tr>
</table>
</center>
</body>
</html>
Step 5:
Now we will create a xmlviewresolver.jsp inside the /WEB-INF/jsp/ folder that provide view for the XmlViewResolver. The code of the xmlviewresolver.jsp is:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>XML View Resolver Example</title>
</head>
<body>
<center>
<table>
<tr>
<td>
<b>This is XML View Resolver Example.</b>
</td>
</tr>
</table>
</center>
</body>
</html>
Step 6:
Now we will create a XmlViewResolverController.java class for control the request. This java class implement AbstractController and return ModelAndView. The code of theXmlViewResolverController.java class is:
packagenet.roseindia.web;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.springframework.web.servlet.ModelAndView;
importorg.springframework.web.servlet.mvc.AbstractController;
publicclassXmlViewResolverControllerextendsAbstractController{
@Override
protectedModelAndView handleRequestInternal(HttpServletRequest request,HttpServletResponse response)throwsException{
StringMess="XmlViewResolver Example";
System.out.println("------>"+Mess);
ModelAndView modelAndView =newModelAndView("xmlviewresolver");
returnmodelAndView;
}
}
Step 7:
Now we will run this application and see the output like:
If user click on upper link then output is:
If user click on lower link then output is:
This is the complete example with using two view resolvers in spring 2.5.
Download code
Download this example code
UrlBasedViewResolver Example in Spring 2.5 MVC
The UrlBasedViewResolver is provides the mapping logical view names and URLs directly that hands over to the view class specified. The UrlBasedViewResolver provides a convenient shape called InternalResourceViewResolver that support JSP, Servlet, JstlViews and TileViews. In this example, we will discuss about how to use of UrlBasedViewResolver in your project.Step 1:
Now we will create a index.jsp file that will have a link to generate user request. The code of theindex.jsp is:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<title>URL Based View Resolver</title>
</head>
<body>
<center>
<a href="urlbasedviewresolver.html">URL Based View Resolver</a>
</center>
</body>
</html>
Step 2:
Now we will customize the the web.xml file for the DispatcherServlet and set index.jsp as a welcome file . The code of the web.xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>/spring</taglib-uri>
<taglib-location>/WEB-INF/spring.tld</taglib-location>
</taglib>
</web-app>
Step 3:
Now we will create dispatcher-servlet.xml inside the /WEB-INF/ folder. In this dispatcher-servlet.xml we will include some code that are important to use UrlBasedViewResolver. The UrlBasedViewresolver much similar to the InternalResourceViewresolver. The code for the UrlBasedViewResolver in thedispatcher-servlet.xml is:
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
Through this view resolver we have direct mapping the url to actual view. In the Spring MVC, every controller return a view after that the view resolver append the prefix and suffix in this view and show the view as response. The full code of the dispatcher-servlet.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<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 class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/urlbasedviewresolver.html">urlBasedViewResolverController</prop>
</props>
</property>
</bean>
<bean name="urlBasedViewResolverController"
class="net.roseindia.web.UrlbasedViewResolver">
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value=
"org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
Step 4:
Now we will create a message.jsp inside the /WEB-INF/jsp/ folder. This jsp file display when controller send response for the user. The code of the message.jsp is:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>URL Based View Resolver Example</title>
</head>
<body>
<center>
<table>
<tr>
<td>
<b>${message}</b>
</td>
</tr>
</table>
</center>
</body>
</html>
Step 5:
Now we will create a controller class for handle the user request that implements the AbstractController. The controller class name is UrlbasedViewResolver.java. This controller class return a message and ModelAndView. The code of the UrlbasedViewResolver.java is:
packagenet.roseindia.web;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.springframework.web.servlet.ModelAndView;
importorg.springframework.web.servlet.mvc.AbstractController;
publicclassUrlbasedViewResolverextendsAbstractController{
@Override
protectedModelAndView handleRequestInternal(HttpServletRequest request,HttpServletResponse response)throwsException{
StringMessage="This is URL Based View Resolver Test Example.";
ModelAndView modelAndView =newModelAndView("message");
modelAndView.addObject("message",Message);
returnmodelAndView;
}
}
Step 6:
Now we will run this application and see the output like:
Now user click on this link and see like:
Download code
BeanNameUrlHandlerMapping Example
BeanNameUrlHandlerMapping example in Spring 2.5 MVC framework
First of all, we will discuss about what HandlerMapping is. The HandlerMapping we can map incoming web request to the appropriate handler. When the user generate Request that reached the DispatcherServlet, the DispatcherServlet find the HandlerMapping object and map these Handler object to the Client request.In this example we will discuss about BeanNameUrlHandlerMapping that provide mapping between request and the appropriate handler object on the basis of Url. We have used Http request as name of bean in the DispatcherServlet configuration file. Now we will provide an example that provided a way to you, how to use BeanNameUrlHandlerMapping in your application. Spring provides BeanNameUrlHandlerMapping by default if you have not include any HandlerMappings.
Step 1:
Now we will create a index.jsp inside the /WebContent/ directory that will have a hyperlink for generate Client request in the web browser. The code of the index.jsp is:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<title>BeanNameUrlHandlerMapping</title>
</head>
<body>
<center>
<a href="beannameurlhandlermapping.html">BeanNameUrlHandlerMapping</a>
</center>
</body>
</html>
Step 2:
Now we will configure the web.xml for DispatcherServlet and set index.jsp as a welcome file. we will also add string.tld file with the help of <taglib> in the web.xml file. The code of the web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http:
//java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>/spring</taglib-uri>
<taglib-location>/WEB-INF/spring.tld</taglib-location>
</taglib>
</web-app>
Step 3:
Now we will create a dispatcher-servlet.xml file inside the /WEB-INF/ project directory. The dispatcher-servlet.xml file contains maps incoming HTTP requests to names of beans by using BeanNameUrlHandlerMapping. The code that are use for this task is:
<bean id="defaultHandlerMapping"class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean name="/beannameurlhandlermapping.html"class="net.roseindia.web.BeanNameUrlHandlerMappingController">
First bean setting provides BeanNameUrlHandlerMapping for the use as a HandlerMappings and second bean setting uses Http request as a name of the bean and provides class to handle this request. The BeanNameUrlHandlerMapping using Url of the Client is directly mapped to the Controller. The code of the dispatcher-servlet.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:p="http://www.springframework.org/schema/p">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="defaultHandlerMapping" class=
"org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean name="/beannameurlhandlermapping.html" class=
"net.roseindia.web.BeanNameUrlHandlerMappingController">
</bean>
</beans>
Step 4:
Now we will create a controller class for handle the client request that's name BeanNameUrlHandlerMappingController.java. The BeanNameUrlHandlerMappingController.java class extends AbstractController that return ModelAndView object. The code of theBeanNameUrlHandlerMappingController.java is:
packagenet.roseindia.web;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.springframework.web.servlet.ModelAndView;
importorg.springframework.web.servlet.mvc.AbstractController;
publicclassBeanNameUrlHandlerMappingControllerextendsAbstractController{
@Override
protectedModelAndView handleRequestInternal(HttpServletRequest request,HttpServletResponse response)throwsException{
StringMess="Bean Name Url Handler Mapping Example";
System.out.println(Mess);
ModelAndView modelAndView =newModelAndView("success");
modelAndView.addObject("message",Mess);
returnmodelAndView;
}
}
Step 5:
The BeanNameUrlHandlerMappingController.java class return success object with message and the viewResolver resolve that append the suffix and prefix this object and return success.jsp so we will create success.jsp file inside the /WEB-INF/jsp/ folder that display message as response. The code of the success.jsp is:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional
//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>BeanNameUrlHandlerMapping Example</title>
</head>
<body>
<center>
<table>
<tr>
<td>
<b>${message}.</b>
</td>
</tr>
</table>
</center>
</body>
</html>
Step 6:
Now we will run this example and see the output like:
After click on this link then a request will generate and display the response like:
Download code
Download this example code
BeanNameUrlHandlerMapping With Command Class Example
BeanNameUrlHandlerMappingWithCommandClass example in Spring 2.5 MVC framework
Learn how to use BeanNameUrlHandlerMapping with CommandClass Part 1.In this example we will used BeanNameUrlHandlerMapping with Command class. You can see what is the process of using command class with BeanNameUrlHandlerMapping handler mapping.
Step 1:
Now we will create a index.jsp inside the /WebContent/ directory that will have a hyperlink for generate Client request in the web browser. The code of the index.jsp is:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<title>BeanNameUrlHandlerMapping using Command Class</title>
</head>
<body>
<center>
<a href="beannameurlhandlermappingwithcommandclass.html">
BeanNameUrlHandlerMapping Using Form</a>
</center>
</body>
</html>
Step 2:
Now we will configure the web.xml for DispatcherServlet and set index.jsp as a welcome file. we will also add string.tld file with the help of <taglib> in the web.xml file. The code of the web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http:
//java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>/spring</taglib-uri>
<taglib-location>/WEB-INF/spring.tld</taglib-location>
</taglib>
</web-app>
Step 3:
Now we will create a dispatcher-servlet.xml file inside the /WEB-INF/ project directory. The dispatcher-servlet.xml file contains maps incoming HTTP requests to names of beans by using BeanNameUrlHandlerMapping. The code that are use for this task is:
<bean id="defaultHandlerMapping" class=
"org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean id="contactValidator" class="net.roseindia.web.ContactValidator"/>
<bean name="/beannameurlhandlermappingwithcommandclass.html"class="net.roseindia.web.BeanNameUrlHandlerMappingController">
<property name="formView"><value>CreateContact</value></property>
<property name="validator"><ref bean="contactValidator"/></property>
<property name="successView"> <value>ContactCreated</value></property>
<property name="commandClass"><value>net.roseindia.web.Contact</value></property>
<property name="commandName"><value>contact</value></property>
</bean>
First bean setting provides BeanNameUrlHandlerMapping for the use as a HandlerMappings. The second bean setting provide a validator class and third bean setting uses Http request as a name of the bean and provides class to handle this request. The BeanNameUrlHandlerMapping using Url of the Client is directly mapped to the Controller. we have also set the properties like formView, validator with reference bean , successView, commandClass and commandName.
Step 4:
Now we will create CreateContact.jsp file inside the /WEB-INF/jsp/ folder that will have a form with user contact information fields, user fill own contact information in this fields. The BeanNameUrlHandlerMappingController display this jsp file as a formView. The code of theCreateContact.jsp is:
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="spring" uri="/spring"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>BeanNameUrlHandlerMapping Example Using Command class</title>
</head>
<body>
<center>
<form:form method="POST" commandName="contact" name="contact">
<table border="2">
<tr>
<td>First Name :</td>
<td><form:input path="fname" /><font color="red">
<form:errors path="fname"/></font></td>
</tr>
<tr>
<td>Last Name</td>
<td><form:input path="lname" /><font color="red">
<form:errors path="lname"/></font></td>
</tr>
<tr>
<td>EMailId :</td>
<td><form:textarea path="emailid" /><font color="red">
<form:errors path="emailid"/></font></td>
</tr>
<tr>
<td>Gender :</td>
<td>
<form:radiobutton path="gender" value="Male" label="Male" />
<form:radiobutton path="gender" value="Female" label="Female" />
<font color="red"><form:errors path="gender"/></font>
</td>
</tr>
<tr>
<td>Address :</td>
<td><form:textarea path="address" /><font color="red">
<form:errors path="address"/></font></td>
</tr>
<tr>
<td>Contact Number :</td>
<td><form:textarea path="contactnumber" /><font color="red">
<form:errors path="contactnumber"/></font></td>
</tr>
<tr>
<td>Country :</td>
<td><form:input path="country" /><font color="red">
<form:errors path="country"/></font></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Create Contact"></td>
</tr>
</table>
</form:form>
</center>
</body>
</html>
Go to Part 2
BeanNameUrlHandlerMappingWithCommandClass example in Spring 2.5 MVC framework Part 2
Step 5:
Now we will create a ContactCreated.jsp for display all information (using command class and command name) that are entered by user. The bean property successView display this file if user fill all information successfully. The code of the ContactCreated.jsp is:
<%@ page session="false"%>
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="spring" uri="/spring" %>
<html>
<head>
<title>BeanNameUrlHandlerMapping Example Using Form</title>
</head>
<body>
<center>
<table>
<tr>
<td colspan="2" align="center"><font size="5">
Contact Information</font></td>
</tr>
<tr>
<td>First Name:</td>
<td><core:out value="${contact.fname}"/></td>
</tr>
<tr>
<td>Last Name:</td>
<td><core:out value="${contact.lname}"/></td>
</tr>
<tr>
<td>EmailId:</td>
<td><core:out value="${contact.emailid}"/></td>
</tr>
<tr>
<td>Gender:</td>
<td><core:out value="${contact.gender}"/></td>
</tr>
<tr>
<td>Address:</td>
<td><core:out value="${contact.address}"/></td>
</tr>
<tr>
<td>Contact Number:</td>
<td><core:out value="${contact.contactnumber}"/></td>
</tr>
<tr>
<td>Country:</td>
<td><core:out value="${contact.country}"/></td>
</tr>
</table>
</center>
</body>
</html>
Step 6:
Now we will create a a controller class that's name BeanNameUrlHandlerMappingController.java for handle user generated request and return ModelAndView with contact class object. The code of theBeanNameUrlHandlerMappingController.java is:
package net.roseindia.web;
import javax.servlet.ServletException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import net.roseindia.web.Contact;
publicclassBeanNameUrlHandlerMappingControllerextendsSimpleFormController{
@Override
protectedModelAndView onSubmit(Object command)throwsServletException{
Contact contact =(Contact) command;
System.out.println(contact.getFname());
System.out.println(contact.getLname());
System.out.println(contact.getGender());
System.out.println(contact.getAddress());
System.out.println(contact.getCountry());
System.out.println(contact.getContactnumber());
System.out.println(contact.getEmailid());
ModelAndView modelAndView =newModelAndView("ContactCreated");
modelAndView.addObject("contact", contact);
return modelAndView;
}
}
Step 7:
Now we will create a Contact.java class inside the project src folder. We have used this class as command class for the user request. This class is a Javabean class that have user contact variables and these setter and getter methods. The code of the Contact.java is:
package net.roseindia.web;
public class Contact {
public Contact(){}
private String fname;
private String lname;
private String gender;
private String address;
private String country;
private String emailid;
private String contactnumber;
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getGender() {
return gender;
}
public void setAddress(String address) {
this.address = address;
}
public String getAddress() {
return address;
}
public void setCountry(String country) {
this.country = country;
}
public String getCountry() {
return country;
}
public void setEmailid(String emailid) {
this.emailid = emailid;
}
public String getEmailid() {
return emailid;
}
public void setContactnumber(String contactnumber) {
this.contactnumber = contactnumber;
}
public String getContactnumber() {
return contactnumber;
}
}
Step 8:
Now we will create a ContactValidator.java class that validate the CreateContact.jsp form fields. The code of the ContactValidator.java is:
package net.roseindia.web;
import java.util.regex.*;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.validation.ValidationUtils;
import net.roseindia.web.Contact;
publicclassContactValidatorimplementsValidator{
@Override
publicboolean supports(Class clazz){
returnContact.class.isAssignableFrom(clazz);
}
publicvoid validate(Object obj,Errors errors){
Contact contact =(Contact) obj;
if((contact.getEmailid()!="")||(contact.getEmailid().length())!=0){
Pattern p=Pattern.compile(".+@.+\\.[a-z]+");
Matcher m=p.matcher(contact.getEmailid());
boolean b=m.matches();
if(b!=true)
{
errors.rejectValue("emailid","error.is.not.valid","Email ID does not Valid ");
}
}
if((contact.getContactnumber()!="")||(contact.getContactnumber().length())!=0){
Pattern pattern =Pattern.compile("\\d{1}-\\d{4}-\\d{6}");
Matcher matcher = pattern.matcher(contact.getContactnumber());
boolean con=matcher.matches();
if(con!=true)
{
errors.rejectValue("contactnumber","error.is.not.valid","Enter Contact Number Like 0-9999-999999");
}
}
if(contact.getFname()==null|| contact.getFname().length()==0){
errors.rejectValue("fname","error.empty.field","Please Enter First Name");
}
if(contact.getLname()==null|| contact.getLname().length()==0){
errors.rejectValue("lname","error.empty.field","Please Enter Last Name");
}
if(contact.getEmailid()==null|| contact.getEmailid().length()==0){
errors.rejectValue("emailid","error.empty.field","Please Enter EmailId");
}
if(contact.getAddress()==null|| contact.getAddress().length()==0){
errors.rejectValue("address","error.empty.field","Please Enter Address");
}
if(contact.getCountry()==null|| contact.getCountry().length()==0){
errors.rejectValue("country","error.empty.field","Please Enter Country");
}
if(contact.getContactnumber()==null||contact.getContactnumber().length()==0){
errors.rejectValue("contactnumber","error.empty.field","Please Enter Contact Number");
}
if(contact.getGender()==null|| contact.getGender().length()==0){
errors.rejectValue("gender","error.empty.field","Please Enter Genter");
}
}
}
Step 9:
Now we will run this example and output is:
If user click on this link then the output is:
If user not fill all information with correct format then the validation called like:
If the user fill all information correct format and click on the button "Create Contact". After that the output is:
Go Back to Part 1
Download code
No comments:
Post a Comment