« Previous | 1 | 2 | 3 | Next »

Spring – Web MVC Framework


The Spring Web MVC framework provides Model-View-Controller (MVC) architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements.
  • The Model encapsulates the application data and in general they will consist of POJO.
  • The View is responsible for rendering the model data and in general it generates HTML output that the client's browser can interpret.
  • The Controller is responsible for processing user requests and building an appropriate model and passes it to the view for rendering.
The DispatcherServlet

The Spring Web MVC framework is designed around a DispatcherServlet that handles all the HTTP requests and responses. The request processing workflow of the Spring Web MVC DispatcherServlet is illustrated in the following diagram:

Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet:
  • After receiving an HTTP request, the DispatcherServlet consults the HandlerMapping to call the appropriate Controller.
  • The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set a model data based on defined business logic and returns the view name to the DispatcherServlet.
  • The DispatcherServlet will take help from the ViewResolver to pick up the defined view for the request.
  • Once the view is finalized, the DispatcherServlet passes the model data to the view, which is finally rendered on the browser.
All the above-mentioned components, i.e. HandlerMapping, Controller, and ViewResolver are parts of WebApplicationContext, which is an extension of the plain ApplicationContext with some extra features necessary for web applications.

Required Configuration

You need to map requests that you want the DispatcherServlet to handle, by using a URL mapping in the web.xml file. The following is an example to show declaration and mapping for HelloWeb DispatcherServlet example:

<web-app id="WebApp_ID" version="2.4"
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_4.xsd">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
</web-app>

The web.xml file will be kept in the WebContent/WEB-INF directory of your web application. Upon initialization of HelloWeb DispatcherServlet, the framework will try to load the application context from a file named [servlet-name]-servlet.xml located in the application's WebContent/WEB-INFdirectory. In this case, our file will be HelloWebservlet. xml.

Next, <servlet-mapping> tag indicates what URLs will be handled by which DispatcherServlet. Here all the HTTP requests ending with .jsp will be handled by the HelloWeb DispatcherServlet.

If you do not want to go with the default filename as [servlet-name]-servlet.xml and the default location as WebContent/WEB-INF, you can customize this file name and location by adding the servlet listener ContextLoaderListener in your web.xml file as follows:

<web-app...>
<!-------- DispatcherServlet definition goes here----->
....
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/HelloWeb-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>

Now, let us check the required configuration for HelloWeb-servlet.xml file, placed in your web application's WebContent/WEB-INF directory:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.jtc" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>

Following are the important points about HelloWeb-servlet.xml file:
  • The [servlet-name]-servlet.xml file will be used to create the beans defined, overriding the definitions of any beans defined with the same name in the global scope.
  • The <context:component-scan...> tag will be used to activate Spring MVC annotation scanning capability, which allows to make use of annotations like @Controller and @RequestMapping, etc.
  • The InternalResourceViewResolver will have rules defined to resolve the view names. As per the above-defined rule, a logical view named hello is delegated to a view implementation located at /WEB-INF/jsp/hello.jsp .
The following section will show you how to create your actual components, i.e., Controller, Model, and View.

Defining a Controller

The DispatcherServlet delegates the request to the controllers to execute the functionality specific to it. The @Controller annotation indicates that a particular class serves the role of a controller. The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.

@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}

The @Controller annotation defines the class as a Spring MVC controller. Here, the first usage of @RequestMapping indicates that all handling methods on this controller are relative to the /hello path. Next annotation@RequestMapping(method = RequestMethod.GET) is used to declare theprintHello() method as the controller's default service method to handle HTTP GET request. You can define another method to handle any POST request at the same URL.

You can write the above controller in another form where you can add additional attributes in @RequestMapping as follows:

@Controller
public class HelloController{
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}

The value attribute indicates the URL to which the handler method is mapped and the method attribute defines the service method to handle HTTP GET request. The following important points are to be noted about the controller defined above:
  • You will define required business logic inside a service method. You can call another method inside this method as per requirement.
  • Based on the business logic defined, you will create a model within this method. You can use setter different model attributes and these attributes will be accessed by the view to present the final result. This example creates a model with its attribute "message".
  • A defined service method can return a String, which contains the name of the view to be used to render the model. This example returns "hello" as logical view name.
Creating JSP Views

Spring MVC supports many types of views for different presentation technologies. These include - JSPs, HTML, PDF, Excel worksheets, XML, Velocity templates, XSLT, JSON, Atom and RSS feeds, JasperReports, etc. But most commonly we use JSP templates written with JSTL.

Let us write a simplehello view in /WEB-INF/hello/hello.jsp:

<html>
<head>
<title>Hello Spring MVC</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>

Here ${message} is the attribute which we have set up inside the Controller. You can have multiple attributes to be displayed inside your view.

Spring Web MVC Framework Examples

Based on the above concepts, let us check few important examples which will help you in building your Spring Web Applications:
Sr. No.Example & Description
1Spring MVC Hello World Example
This example will explain how to write a simple Spring Web Hello World application.
2Spring MVC Form Handling Example
This example will explain how to write a Spring Web application using HTML forms to submit the data to the controller and display a processed result.
3Spring Page Redirection Example
Learn how to use page redirection functionality in Spring MVC Framework.
4Spring Static Pages Example
Learn how to access static pages along with dynamic pages in Spring MVC Framework.
5Spring Exception Handling Example
Learn how to handle exceptions in Spring MVC Framework.
Spring MVC Hello World Example

The following example shows how to write a simple web-based Hello World application using Spring MVC framework. To start with it, let us have a working Eclipse IDE in place and take the following steps to develop a Dynamic Web Application using Spring Web Framework:
StepsDescription
1Create a Dynamic Web Project with a name HelloWeb and create a packagecom.jtc under the src folder in the created project.
2Drag and drop the below-mentioned Spring and other libraries into the folderWebContent/WEB-INF/lib.
3Create a Java class HelloController under the com.jtc package.
4Create Spring configuration files web.xml and HelloWeb-servlet.xml under the WebContent/WEB-INF folder.
5Create a sub-folder with a name jsp under the WebContent/WEB-INFfolder. Create a view file hello.jsp under this sub-folder.
6The final step is to create the content of all the source and configuration files and export the application as explained below.
Here is the content of HelloController.java file

package com.jtc;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}

Following is the content of Spring Web configuration file web.xml

<web-app id="WebApp_ID" version="2.4"
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_4.xsd">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

Following is the content of another Spring Web configuration file HelloWeb-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.jtc" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>

Following is the content of Spring view file hello.jsp

<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>

Finally, following is the list of Spring and other libraries to be included in your web application. You simply drag these files and drop them in WebContent/WEBINF/ lib folder.
  • commons-logging-x.y.z.jar
  • org.springframework.asm-x.y.z.jar
  • org.springframework.beans-x.y.z.jar
  • org.springframework.context-x.y.z.jar
  • org.springframework.core-x.y.z.jar
  • org.springframework.expression-x.y.z.jar
  • org.springframework.web.servlet-x.y.z.jar
  • org.springframework.web-x.y.z.jar
  • spring-web.jar
Once you are done creating the source and configuration files, export your application. Right-click on your application and use Export > WAR File option and save your HelloWeb.war file in Tomcat's webapps folder.

Now start your Tomcat server and make sure you are able to access other web pages from webapps folder using a standard browser. Try to access the URL http://localhost:8080/HelloWeb/hello and if everything is fine with your Spring Web Application, you should see the following result:

You should note that in the given URL, HelloWeb is the application name and hello is the virtual subfolder, which we have mentioned in our controller using @RequestMapping("/hello"). You can use the direct root while mapping your URL using @RequestMapping("/"). In this case, you can access the same page using short URL http://localhost:8080/HelloWeb/ but it is advised to have different functionalities under different folders.

Spring MVC Form Handling Example

The following example shows how to write a simple web-based application, which makes use of HTML forms using Spring Web MVC framework. To start with, let us have a working Eclipse IDE in place and take the following steps to develope a Dynamic Form-based Web Application using Spring Web Framework:
StepsDescription
1Create a Dynamic Web Project with a name HelloWeb and create a packagecom.jtc under the src folder in the created project.
2Drag and drop the below-mentioned Spring and other libraries into the folderWebContent/WEB-INF/lib.
3Create a Java classes Student and StudentController under the com.jtc package.
4Create Spring configuration files Web.xml and HelloWeb-servlet.xml under the WebContent/WEB-INF folder.
5Create a sub-folder with a name jsp under the WebContent/WEB-INFfolder. Create a view files student.jsp and result.jsp under this sub-folder.
6The final step is to create the content of all the source and configuration files and export the application as explained below.
Here is the content of Student.java file

package com.jtc;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}

Following is the content of StudentController.java file

package com.jtc;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class StudentController {
@RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("student", "command", new Student());
@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(@ModelAttribute("SpringWeb")Student student,
ModelMap model) {
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
return "result";
}
}
}

Here the first service method student(), we have passed a blank Student object in the ModelAndView object with the name "command" because the Spring framework expects an object with the name "command" if you are using <form:form> tags in your JSP file. So, when student() method is called, it returns student.jsp view.

The second service method addStudent() will be called against a POST method on the HelloWeb/addStudent URL. You will prepare your model object based on the submitted information. Finally, a "result" view will be returned from the service method, which will result in rendering result.jsp

Following is the content of Spring Web configuration file web.xml

<web-app id="WebApp_ID" version="2.4"
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_4.xsd">
<display-name>Spring MVC Form Handling</display-name>
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

Following is the content of another Spring Web configuration file HelloWeb-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.jtc" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>

Following is the content of Spring view file student.jsp

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Student Information</h2>
<form:form method="POST" action="/HelloWeb/addStudent">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><form:label path="age">Age</form:label></td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td><form:label path="id">id</form:label></td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>

Following is the content of Spring view file result.jsp

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
<tr>
<td>ID</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>

Finally, following is the list of Spring and other libraries to be included in your web application. You simply drag these files and drop them in WebContent/WEBINF/ lib folder.
  • commons-logging-x.y.z.jar
  • org.springframework.asm-x.y.z.jar
  • org.springframework.beans-x.y.z.jar
  • org.springframework.context-x.y.z.jar
  • org.springframework.core-x.y.z.jar
  • org.springframework.expression-x.y.z.jar
  • org.springframework.web.servlet-x.y.z.jar
  • org.springframework.web-x.y.z.jar
  • spring-web.jar
Once you are done creating the source and configuration files, export your application. Right-click on your application and use the Export > WAR File option and save your SpringWeb.war file in Tomcat's webapps folder.

Now start your Tomcat server and make sure you are able to access other web pages from webapps folder using a standard browser. Try a URL http://localhost:8080/SpringWeb/student and you should see the following result if everything is fine with your Spring Web Application.

After submitting the required information, click the Submit button to submit the form. You should see the following result if everything is fine with your Spring Web Application.

Spring Page Redirection Example

The following example show how to write a simple web-based application which makes use of redirect to transfer a http request to another page. To start with, let us have a working Eclipse IDE in place and take the following steps to develop a Dynamic Formbased Web Application using Spring Web Framework:
StepsDescription
1Create a Dynamic Web Project with a name HelloWeb and create a packagecom.jtc under the src folder in the created project.
2Drag and drop the below-mentioned Spring and other libraries into the folderWebContent/WEB-INF/lib.
3Create a Java class WebController under the com.jtc package.
4Create Spring configuration files Web.xml and HelloWeb-servlet.xml under the WebContent/WEB-INF folder.
5Create a sub-folder with a name jsp under the WebContent/WEB-INFfolder. Create view files index.jsp and final.jsp under this sub-folder.
6The final step is to create the content of all the source and configuration files and export the application as explained below.
Here is the content of WebController.java file

package com.jtc;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class WebController {
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index() {
return "index";
}
@RequestMapping(value = "/redirect", method = RequestMethod.GET)
public String redirect() {
return "redirect:finalPage";
}
@RequestMapping(value = "/finalPage", method = RequestMethod.GET)
public String finalPage() {
return "final";
}
}

Following is the content of Spring Web configuration file web.xml

<web-app id="WebApp_ID" version="2.4"
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_4.xsd">
<display-name>Spring Page Redirection</display-name>
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

Following is the content of another Spring Web configuration file HelloWeb-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.jtc" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>

Following is the content of Spring view file index.jsp. This will be a landing page, this page will send a request to access redirect service method, which will redirect this request to another service method and finally a final.jsp page will be displayed.

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring Page Redirection</title>
</head>
<body>
<h2>Spring Page Redirection</h2>
<p>Click below button to redirect the result to new page</p>
<form:form method="GET" action="/HelloWeb/redirect">
<table>
<tr>
<td>
<input type="submit" value="Redirect Page"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>

Following is the content of Spring view file final.jsp. This is the final redirected page.

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring Page Redirection</title>
</head>
<body>
<h2>Redirected Page</h2>
</body>
</html>

Finally, following is the list of Spring and other libraries to be included in your web application. You simply drag these files and drop them in WebContent/WEBINF/ lib folder.
  • commons-logging-x.y.z.jar
  • org.springframework.asm-x.y.z.jar
  • org.springframework.beans-x.y.z.jar
  • org.springframework.context-x.y.z.jar
  • org.springframework.core-x.y.z.jar
  • org.springframework.expression-x.y.z.jar
  • org.springframework.web.servlet-x.y.z.jar
  • org.springframework.web-x.y.z.jar
  • spring-web.jar
Once you are done creating the source and configuration files, export your application. Right-click on your application and use the Export > WAR File option and save your HelloWeb.war file in Tomcat's webapps folder.

Now start your Tomcat server and make sure you are able to access other web pages from webapps folder using a standard browser. Try a URL http://localhost:8080/HelloWeb/index and you should see the following result if everything is fine with your Spring Web Application.

Click the "Redirect Page" button to submit the form and to get the final redirected page. You should see the following result if everything is fine with your Spring Web Application.

Spring Static Pages Example

The following example shows how to write a simple web-based application using Spring MVC Framework, which can access static pages along with dynamic pages with the help of <mvc:resources> tag. To start with, let us have a working Eclipse IDE in place and take the following steps to develope a Dynamic Form based Web Application using Spring Web Framework:
StepsDescription
1Create a Dynamic Web Project with a name HelloWeb and create a packagecom.jtc under the src folder in the created project.
2Drag and drop the below-mentioned Spring and other libraries into the folderWebContent/WEB-INF/lib.
3Create a Java class WebController under the com.jtc package.
4Create Spring configuration files Web.xml and HelloWeb-servlet.xml under the WebContent/WEB-INF folder.
5Create a sub-folder with a name jsp under the WebContent/WEB-INFfolder. Create a view file index.jsp under this sub-folder.
6Create a sub-folder with a name pages under the WebContent/WEB-INFfolder. Create a static file final.htm under this sub-folder.
7The final step is to create the content of all the source and configuration files and export the application as explained below.
Here is the content of WebController.java file

package com.jtc;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class WebController {
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index() {
return "index";
}
@RequestMapping(value = "/staticPage", method = RequestMethod.GET)
public String redirect() {
return "redirect:/pages/final.htm";
}
}

Following is the content of Spring Web configuration file web.xml

<web-app id="WebApp_ID" version="2.4"
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_4.xsd">
<display-name>Spring Page Redirection</display-name>
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

Following is the content of another Spring Web configuration file HelloWeb-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.jtc" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean> <mvc:resources mapping="/pages/**" location="/WEB-INF/pages/" />
<mvc:annotation-driven/>
</beans>

Here <mvc:resources..../> tag is being used to map static pages. The mapping attribute must be an Ant pattern that specifies the URL pattern of an http requests. The location attribute must specify one or more valid resource directory locations having static pages including images, stylesheets, JavaScript, and other static content. Multiple resource locations may be specified using a comma-seperated list of values.

Following is the content of Spring view file WEB-INF/jsp/index.jsp. This will be a landing page; this page will send a request to access staticPage service method, which will redirect this request to a static page available in WEB-INF/pages folder.

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring Landing Page</title>
</head>
<body>
<h2>Spring Landing Pag</h2>
<p>Click below button to get a simple HTML page</p>
<form:form method="GET" action="/HelloWeb/staticPage">
<table>
<tr>
<td>
<input type="submit" value="Get HTML Page"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>

Following is the content of Spring view file WEB-INF/pages/final.htm

<html>
<head>
<title>Spring Static Page</title>
</head>
<body>
<h2>A simple HTML page</h2>
</body>
</html>

Finally, following is the list of Spring and other libraries to be included in your web application. You simply drag these files and drop them in WebContent/WEBINF/ lib folder.
  • commons-logging-x.y.z.jar
  • org.springframework.asm-x.y.z.jar
  • org.springframework.beans-x.y.z.jar
  • org.springframework.context-x.y.z.jar
  • org.springframework.core-x.y.z.jar
  • org.springframework.expression-x.y.z.jar
  • org.springframework.web.servlet-x.y.z.jar
  • org.springframework.web-x.y.z.jar
  • spring-web.jar
Once you are done creating the source and configuration files, export your application. Right-click on your application and use Export > WAR File option and save your HelloWeb.war file in Tomcat's webapps folder.

Now start your Tomcat server and make sure you are able to access other web pages from webapps folder using a standard browser. Try to access the URL http://localhost:8080/HelloWeb/index. If everything is fine with your Spring Web Application, you should see the following result:

Click the "Get HTML Page" button to access a static page mentioned in staticPage service method. If everything is fine with your Spring Web Application, you should see the following result.

Spring Exception Handling Example

The following example shows how to write a simple web-based application using Spring MVC Framework, which can handle one or more exceptions raised inside its controllers. To start with, let us have a working Eclipse IDE in place and take the following steps to develop a Dynamic Form-based Web Application using Spring Web Framework:
StepsDescription
1Create a Dynamic Web Project with a name HelloWeb and create a packagecom.jtc under the src folder in the created project.
2Drag and drop the below-mentioned Spring and other libraries into the folderWebContent/WEB-INF/lib.
3
4Create Spring configuration files Web.xml and HelloWeb-servlet.xml under the WebContent/WEB-INF folder.
5Create a sub-folder with a name jsp under the WebContent/WEB-INFfolder. Create a view files student.jsp, result.jsp, error.jsp, andExceptionPage.jsp under jsp sub-folder.
6The final step is to create the content of all the source and configuration files and export the application as explained below.
Following is the content of Student.java file

package com.jtc;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}

Following is the content of SpringException.java file

package com.jtc;
public class SpringException extends RuntimeException{
private String exceptionMsg;
public SpringException(String exceptionMsg) {
this.exceptionMsg = exceptionMsg;
}
public String getExceptionMsg(){
return this.exceptionMsg;
}
public void setExceptionMsg(String exceptionMsg) {
this.exceptionMsg = exceptionMsg;
}
}

Following is the content of StudentController.java file. Here, you need to annotate a service method using @ExceptionHandler where you can specify one or more exceptions to be handled. If you are specifying more than one exception then you can use comma separated values.

package com.jtc;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class StudentController {
@RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("student", "command", new Student());
}
@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
@ExceptionHandler({SpringException.class})
public String addStudent( @ModelAttribute("HelloWeb")Student student,
ModelMap model) {
if(student.getName().length() < 5 ){
throw new SpringException("Given name is too short");
}else{
model.addAttribute("name", student.getName());
}
if( student.getAge() < 10 ){
throw new SpringException("Given age is too low");
}else{
model.addAttribute("age", student.getAge());
}
model.addAttribute("id", student.getId());
return "result";
}
}

Following is the content of Spring Web configuration file web.xml

<web-app id="WebApp_ID" version="2.4"
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_4.xsd">
<display-name>Spring Exception Handling</display-name>
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

Following is the content of another Spring Web configuration file HelloWeb-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.jtc" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean class="org.springframework.web.servlet.handler.
SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.jtc.SpringException">
ExceptionPage
</prop>
</props>
</property>
<property name="defaultErrorView" value="error"/>
</bean>
</beans>

Here you specified ExceptionPage as an exception view in case SpringException occurs, if there is any other type of exception then a generic view error will take place.

Following is the content of Spring view file student.jsp

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Exception Handling</title>
</head>
<body>
<h2>Student Information</h2>
<form:form method="POST" action="/HelloWeb/addStudent">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><form:label path="age">Age</form:label></td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td><form:label path="id">id</form:label></td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>

Following is the content of Spring view fileerror.jsp

<html>
<head>
<title>Spring Error Page</title>
</head>
<body>
<p>An error occured, please contact webmaster.</p>
</body>
</html>;

Following is the content of Spring view file ExceptionPage.jsp. Here you will access the exception instance via ${exception}.

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Exception Handling</title>
</head>
<body>
<h2>Spring MVC Exception Handling</h2>
<h3>${exception.exceptionMsg}</h3>
</body>
</html>

Following is the content of Spring view file result.jsp

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html><br>
<head><br>
<title>Spring MVC Form Handling/title><br>
</head><br>
<body><br>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
<tr>
<td>ID</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>

Finally, following is the list of Spring and other libraries to be included in your web application. You simply drag these files and drop them in WebContent/WEBINF/ lib folder.
  • commons-logging-x.y.z.jar
  • org.springframework.asm-x.y.z.jar
  • org.springframework.beans-x.y.z.jar
  • org.springframework.context-x.y.z.jar
  • org.springframework.core-x.y.z.jar
  • org.springframework.expression-x.y.z.jar
  • org.springframework.web.servlet-x.y.z.jar
  • org.springframework.web-x.y.z.jar
  • spring-web.jar
Once you are done creating the source and configuration files, export your application. Right-click on your application and use the Export > WAR File option and save your HelloWeb.war file in Tomcat's webapps folder.

Now start your Tomcat server and make sure you are able to access other web pages from webapps folder using a standard browser. Now try to access the URL http://localhost:8080/HelloWeb/student. If everything is fine with your Spring Web Applicationand, you should see the following result.

Enter the values as shown above and click the Submit buttom. If everything is fine with your Spring Web Application, you should see the following result.
« Previous | 1 | 2 | 3 | Next »


copyright © 2014 - all rights riserved by javatechnologycenter.com