dineshonjava

How to write RESTful web services using spring mvc

Spring is a well-known framework for building Java™ Platform, Enterprise Edition (Java EE) applications, now it supports Representational State Transfer (REST) in its Model-View-Controller (MVC) layer. It's important for RESTful web services to produce multiple representations based on the client requests. In this article, learn how to use Spring APIs and annotations to build RESTful web services that produce popular representations such as ATOM Feed, XML, and JavaScript Object Notation (JSON).
What is REST?
REST is an architectural style that has evolved from existing web technologies to allow client applications to communicate with a server using a simple and familiar approach. The approach is familiar because REST is built on top of the HTTP protocol, a protocol that has formed the backbone of the web for years. REST leverages the existing capabilities of HTTP and uses them to provide an architectural approach for implementing a simple and effective client server model.

RESTFul webservices: A RESTFul webservices are based on the HTTP methods and the concept of REST. A RESTFul webservice typically defines the base URI for the services, the supported MIME-types (XML, Text, JSON, user-defined,..) and the set of operations (POST, GET, PUT, DELETE) which are supported.


REST support in Spring3MVC:
@Controller:-
Use the @Controller annotation to annotate the class that will be the controller in MVC and handle the HTTP request.



@RequestMapping:-
Use the @RequestMapping annotation to annotate the function that should handle certain HTTP methods, URIs, or HTTP headers. This annotation is the key to the Spring REST support. You change the method parameter to handle other HTTP methods.
For example:
@RequestMapping(method=RequestMethod.GET, value="/emps",
headers="Accept=application/xml, application/json")

 

 @PathVariable:-
A path variable in the URI could be injected as a parameter using the @PathVariable annotation.
For example:
@RequestMapping(method=RequestMethod.GET, value="/emp/{id}")
public ModelAndView getEmployee(@PathVariable String id) { … }


Other useful annotations
Use @RequestParam to inject a URL parameter into the method.
Use @RequestHeader to inject a certain HTTP header into the method.
Use @RequestBody to inject an HTTP request body into the method.
Use @ResponseBody to return the content or object as the HTTP response body.
Use HttpEntity to inject into the method automatically if you provide it as a parameter.
Use ResponseEntity to return the HTTP response with your custom status or headers.
For example:
public @ResponseBody Employee getEmployeeById(@RequestParam("name")
String name, @RequestHeader("Accept") String accept, @RequestBody String body) {…}
public ResponseEntity
method(HttpEntity entity) {…}
 

For writing the web application which support RESTfull url then we have follow the steps.
Step 1: Adding the following another jars to the Libs folder.
jaxb-api-2.1.jar
jaxen-1.1.1.jar


Step 2: Update bean configuration file (sdnext-servlet.xml) for view resolvers.
<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" 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
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

   <mvc:annotation-driven></mvc:annotation-driven>
 
   <context:component-scan base-package="com.dineshonjava.web">
   </context:component-scan>

  <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
     <property name="mediaTypes">
       <map>
   <entry key="html" value="text/html"></entry>
   <entry key="json" value="application/json"></entry>
   <entry key="xml" value="application/xml"></entry>
 </map>
     </property>
     <property name="viewResolvers">
 <list>
  <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView">
            </property>
     <property name="prefix" value="/WEB-INF/views/"></property>
     <property name="suffix" value=".jsp"></property>
   </bean>
 </list>
     </property>
  </bean>
</beans>
Step 3: Add model classes: There are two model classes Employee.java and Employees.java
These classes will be having JAXB annotations, which will be used by marshaller to convert them in appropriate xml or json formats.
Employees.java
package com.dineshonjava.web.model;

import java.util.Collection;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author Dinesh Rajput
 *
 */
@XmlRootElement(name="employees")
@XmlAccessorType(XmlAccessType.NONE)
public class Employees {
 @XmlElement(name="employee")
 private Collection<Employee> employees;

 public Collection<Employee> getEmployees() {
  return employees;
 }

 public void setEmployees(Collection<Employee> employees) {
  this.employees = employees;
 }
}
Now write Employee.java
package com.dineshonjava.web.model;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author Dinesh Rajput
 *
 */
@XmlRootElement(name="employees")
@XmlAccessorType(XmlAccessType.NONE)
public class Employee {
 @XmlElement(name="empId")
 private Integer id;
 @XmlElement(name="empName")
 private String name;
 @XmlElement(name="empAge")
 private Integer age;
 @XmlElement(name="empSalary")
 private Long salary;
 @XmlElement(name="empAddress")
 private String address;
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public Integer getAge() {
  return age;
 }
 public void setAge(Integer age) {
  this.age = age;
 }
 public Long getSalary() {
  return salary;
 }
 public void setSalary(Long salary) {
  this.salary = salary;
 }
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }
}
Step 4: Write the controller - WebServiceController.java
Our WebServiceController.java will created to have REST specific annotations for path mappings in request parameters mappings. Also, we will specify the header attributes for request and response.
package com.dineshonjava.web.controller;

import java.util.ArrayList;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dineshonjava.web.model.Employee;
import com.dineshonjava.web.model.Employees;

/**
 * @author Dinesh Rajput
 *
 */
@Controller
@RequestMapping("/employees")
public class WebServiceController {
 
 @RequestMapping(method = RequestMethod.GET, value="/{id}", headers="Accept=*/*")
 public @ResponseBody Employee getEmployeeById(@PathVariable String id){
  Employee employee = new Employee();
  employee.setId(1);
  employee.setSalary(50000l);
  employee.setName("Dinesh Rajput");
  employee.setAge(26);
  employee.setAddress("Sector 49-Noida");
  return employee;
 }
 
 @RequestMapping(method = RequestMethod.GET,  headers="Accept=*/*")
 public @ResponseBody Employees getEmployees(){
  Employees employees = new Employees();
  
  Employee employee1 = new Employee();
  employee1.setId(2);
  employee1.setSalary(50000l);
  employee1.setName("Dinesh Rajput");
  employee1.setAge(26);
  employee1.setAddress("Sector 49- Noida");
  
  Employee employee2 = new Employee();
  employee2.setId(3);
  employee2.setSalary(20000l);
  employee2.setName("Anamika Rajput");
  employee2.setAge(26);
  employee2.setAddress("Sector 49- Noida");
  employees.setEmployees(new ArrayList<Employee>());
  employees.getEmployees().add(employee1);
  employees.getEmployees().add(employee2);
  return employees;
 }
}
web.xml
<web-app version="2.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemalocation="http://java.sun.com/xml/ns/javaee 
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

 <servlet>
    <servlet-name>sdnext</servlet-name>
    <servlet-class>
               org.springframework.web.servlet.DispatcherServlet
            </servlet-class>
  <init-param>
            <param-name>contextConfigLocation</param-name><param-value>/WEB-INF/config/sdnext-servlet.xml</param-value></init-param>
        <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>sdnext</servlet-name>
  <url-pattern>*.html</url-pattern>
 </servlet-mapping>

 <welcome-file-list>
  <welcome-file>index.html</welcome-file>
 </welcome-file-list>
</web-app>
Now lets deploy the application on tomcat and hit the URL on any REST client. I am using RESTClient. This is a firefox plugin for testing the RESTful webservices.

RESTfull
Using URL: http://localhost:8080/sdnext/employees/3.html
Now see the following result-
How to write RESTful web services using spring mvc
Download Application (Source+Libs)
Spring3WebServiceApp.zip 


 <<Spring Web MVC Framework |index| Spring Logging with Log4J>> 




Spring 3 MVC Internationalization & Localization with Example

In this chapter we will discuss about Internationalization (I18N) and Localization (L10N) in Spring 3.0 MVC.

What is i18n and L10n?
In computing, internationalization and localization are means of adapting computer software to different languages and regional differences. Internationalization is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. Localization is the process of adapting internationalized software for a specific region or language by adding locale-specific components and translating text.
The terms are frequently abbreviated to the numerous i18n (where 18 stands for the number of letters between the first i and last n in internationalization) and L10n respectively, due to the length of the words. The capital L in L10n helps to distinguish it from the lowercase i in i18n.
Popular Spring Tutorials
  1. Spring Tutorial
  2. Spring MVC Web Tutorial
  3. Spring Boot Tutorial
  4. Spring JDBC Tutorial
  5. Spring AOP Tutorial
  6. Spring Security Tutorial
Now lets we create an application which support multiple languages. We will add two languages support to our application: English and German. Depending on the locale setting of users browser, the appropriate language will be selected.

Step 1: First we create the properties file for the different languages.
  1. messages_en.properties
  2. messages_de.properties
resources/messages_en.properties
emp.label.id=Employee Id
emp.label.name=Employee Name
emp.label.age=Employee Age
emp.label.salary=Salary
emp.label.address=Address
 
label.menu=Menu
label.title=Employee Management System
 
label.footer=© www.dineshonjava.com

resources/messages_de.properties
emp.label.id=Impelyee Id
emp.label.name=Impelyee Vorname
emp.label.age=Impelyee iage
emp.label.salary=shalery
emp.label.address=Adrrezz
 
label.menu=MenĂ¼
label.title=Impelyee Managemenot Sistom
 
label.footer=© www.dineshonjava.com
Step 2: Configure i18n & l10n to Spring3MVC
we need to declare these files in spring configuration file. We will use class org.springframework.context.support.ReloadableResourceBundleMessageSource to define the message resources. Also, note that we will provide a feature where user will be able to select language for the application. This is implemented by using org.springframework.web.servlet.i18n.LocaleChangeInterceptor class. The LocaleChangeInterceptor class will intercept any changes in the locale. These changes are then saved in cookies for future request. org.springframework.web.servlet.i18n.CookieLocaleResolverclass will be used to store the locale changes in cookies.
Add following code in the sdnext-servlet.xml file.
<bean class="org.springframework.context.support.ReloadableResourceBundleMessageSource" id="messageSource">
    <property name="basename" value="classpath:messages"></property>
    <property name="defaultEncoding" value="UTF-8"></property>
</bean>
 
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" id="localeChangeInterceptor">
    <property name="paramName" value="lang"></property>
</bean>
 
<bean class="org.springframework.web.servlet.i18n.CookieLocaleResolver" id="localeResolver">
    <property name="defaultLocale" value="en"></property>
</bean>
 
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" id="handlerMapping">
    <property name="interceptors">
        <ref bean="localeChangeInterceptor"></ref>
    </property>
</bean>
Note that in above configuration we have defined basename property in messageSource bean to classpath:messages. By this, spring will identify that the message resource message_ will be used in this application.
Change in the JSPs Template:
WebRoot/WEB-INF/views/header.jsp

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
 

<spring:message code="emp.label.title"></spring:message>

<span style="float: right;"> <a href="?lang=en">en</a> | <a href="?lang=de">de</a> </span>
WebContent/WEB-INF/views/menu.jsp
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
 
<spring:message code="emp.label.menu"></spring:message>



Spring MVC Interceptor with Example

What is Spring MVC Interceptor? In Web application when request comes to the controller , the HandlerMapping handler matches the incoming request. DispatcherServlet will hand it over to the handler mapping, to let it inspect the request and come up with an appropriate HandlerExecutionChain. Then the DispatcherServlet will execute the handler and interceptors in the chain. When it comes to interceptors you can perform the your logic like logging, method tracking etc. Lets see In below Request Flow Diagram of Spring3MVC framework as discuss in the earlier chapter.

Spring MVC Interceptor with Example

As diagram we can see that Spring3MVC Interceptor framework intercepts an incoming HTTP request before it reaches your Spring MVC controller class, or conversely, intercepts the outgoing HTTP response after it leaves your controller, but before it’s fed back to the browser.

Why we use Spring3 MVC Interceptor? 
The answer is that it allows you to perform tasks that are common to every request or set of requests without the need to cut ‘n’ paste boiler plate code into every controller class. For example, you could perform user authentication of a request before it reaches your controller and, if successful, retrieve some additional user details from a database adding them to the HttpServletRequest object before your controller is called. Your controller can then simply retrieve and use these values or leave them for display by the JSP. On the other hand, if the authentication fails, you could re-direct your user to a different page.


Quick Overview of Spring Interceptor:
Each interceptor you define must implement org.springframework.web.servlet.HandlerInterceptor interface. There are three methods that need to be implemented.


1. preHandle(..) --  is called before the actual handler is executed.
The preHandle(..) method returns a Boolean value. You can use this method to break or continue the processing of the execution chain. When this method returns true, the handler execution chain will continue; when it returns false, the DispatcherServlet assumes the interceptor itself has taken care of requests (and, for example, rendered an appropriate view) and does not continue executing the other interceptors and the actual handler in the execution chain.

2. postHandle(..) --  is called after the handler is executed.

3. afterCompletion(..) -- is called after the complete request has finished.

These three methods should provide enough flexibility to do all kinds of preprocessing and postprocessing.

package com.dineshonjava.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Dinesh Rajput
 *
 */
public class HelloWorldInterceptor implements HandlerInterceptor {

 @Override
 public void afterCompletion(HttpServletRequest request,
   HttpServletResponse response, Object object, Exception exception)
   throws Exception {

 }

 @Override
 public void postHandle(HttpServletRequest request, HttpServletResponse response,
   Object object, ModelAndView modelAndView) throws Exception {

 }

 @Override
 public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
   Object object) throws Exception {
  return false;
 }
}
Once the interceptor is defined, you can ask Spring MVC to configure it via <mvc:interceptors> tag within sdnext-servlet.xml file.
<mvc:interceptors>
  <bean class="com.dineshonjava.interceptor.HelloWorldInterceptor"></bean>
</mvc:interceptors> 
Let us start with the complete application for interceptor. We will create a HelloWorldInterceptor that logs and tracks each coming requests.

In this example show how to write a simple web based Hello World application using Spring 3.0 MVC Interceptor framework. To start with it, let us have working with STS IDE in place and follow the following steps to develop a Dynamic Web Application using Spring 3.0 Web MVC Framework:

Step 1: Create a Dynamic Web Project with a name Spring3MVCInterceptorApp and create two packages com.dineshonjava.controller and
com.dineshonjava.interceptor under the src folder in the created project.

Step 2: Add below mentioned Spring 3.0 libraries and other libraries into the folder WebRoot/WEB-INF/lib

/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/commons-fileupload-1.1.1.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/commons-io-1.2.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/commons-logging-1.1.1.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/hibernate-validator-4.0.2.GA.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/jstl-1.2.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/log4j-1.2.14.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/servlet-2.3.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/slf4j-api-1.5.6.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/slf4j-log4j12-1.5.6.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/spring-asm-3.0.3.RELEASE.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/spring-beans-3.0.3.RELEASE.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/spring-context-3.0.3.RELEASE.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/spring-core-3.0.3.RELEASE.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/spring-expression-3.0.3.RELEASE.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/spring-web-3.0.3.RELEASE.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/spring-webmvc-3.0.3.RELEASE.jar
/SpringMVCHelloWorld/WebRoot/WEB-INF/lib/validation-api-1.0.0.GA.jar 


Step 3: Create a Java class HelloWorldController under the com.dineshonjava.controller package and another
HelloWorldInterceptor under the com.dineshonjava.interceptor package.

Step 4: Create Spring configuration files Web.xml and sdnext-servlet.xml under the WebRoot/WEB-INF/  folder.

Step 5: Create a sub-folder with a name views under the WebRoot/WEB-INF folder. Create a view file hello.jsp under this sub-folder.

Step 6: The final step is to create the content of all the source and configuration files name sdnext-servlet.xml under the sub-folder WebRoot/WEB-INF/config and export the application as explained below.


Software versions used to run the sample code:
  • Spring 3.0
  • Java 1.6
  • Tomcat 7
  • JSTL 1.2
  • STS Java EE IDE
Web Application Structure:
Spring MVC Interceptor
 Now we create the HelloWorldController file.

HelloWorldController.java
package com.dineshonjava.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author Dinesh Rajput
 *
 */
@Controller
@RequestMapping("/hello")
public class HelloWorldController {
 
 @RequestMapping(method = RequestMethod.GET)
 public String sayHelloWorld(ModelMap model) {
  model.addAttribute("message", "Spring 3.0 MVC Framework Hello World Example with Interceptor!");
  model.addAttribute("auther", "DineshOnJava");
  return "hello";
 }
}

The controller has one method sayHelloWorld() which is mapped to URL /hello using @RequestMapping. This simply paints the hello.jsp view.

hello.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<html>
 <head>
    <title>Spring 3.0 MVC Hello World Example</title>
 </head>
 <body>
 <h2>
${message} </h2>
 <h2>
${auther} </h2>
</body>
</html>

Following is the content of Spring Web configuration file web.xml
<web-app id="WebApp_ID" version="3.0" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

  <display-name>SpringMVCHelloWorld</display-name>
  <welcome-file-list>
 <welcome-file>/</welcome-file>
  </welcome-file-list>
 
    <servlet>
        <servlet-name>sdnext</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
      <init-param>
            <param-name>contextConfigLocation</param-name><param-value>/WEB-INF/config/sdnext-servlet.xml</param-value></init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>sdnext</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

Following is the content of another Spring Web configuration file sdnext-servlet.xml
<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" 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
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<!-- Enable annotation driven controllers, validation etc... -->
<mvc:annotation-driven></mvc:annotation-driven>

<context:component-scan base-package="com.dineshonjava.controller">
</context:component-scan>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver">
 <property name="prefix" value="/WEB-INF/views/"></property>
 <property name="suffix" value=".jsp"></property>
</bean>

<mvc:interceptors>
     <bean class="com.dineshonjava.interceptor.HelloWorldInterceptor"></bean>
</mvc:interceptors> 
 
</beans>

Once you are done with creating source and configuration files, export your application. Right click on your application and use Export -> WAR File option and save your Spring3MVCInterceptorApp.war file in Tomcat's web apps folder.

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


Spring MVC Interceptor with Example
 Download Source Code+Libs
Spring3MVCInterceptorApp.zip 




<<Spring Web MVC Framework |index| Spring 3 MVC Internationalization & Localization with Example>>  


Spring MVC Tiles Plugin with Example

In this tutorial we will discuss about the tiles and build a simple SpringMVC  application that utilizes templates using the Apache Tile 3 framework. Now we will create a template version of our pages, and compare it with non-template versions of the same pages. We will split the content, style, and template of these pages logically.
What is Apache Tiles 3.0.1?
Apache Tiles is a templating framework built to simplify the development of web application user interfaces.

Apache Tiles is a popular and mostly used templating framework for java based web application. Tiles became more popular because Struts 1.x uses Tiles as its default templating framework. Spring3MVC which is an MVC framework, like Struts, also supports integration of Tiles as its templating framework.

Tiles allows developer to define page fragments(or parts) which can be assembled into a complete page at run-time. These fragments, or tiles, can be used as simple includes in order to reduce the duplication of common page elements or embedded within other tiles to develop a series of reusable templates. These templates streamline the development of a consistent look and feel across an entire application.


Let us see how we can integrate Spring3MVC and Tiles.
You can download Tiles binaries from here

Application Layout


Spring 3 MVC Tiles Plugin with Example

A web portal have many reusable templates like header, footer, menu etc. These elements remains same in every web page to give a uniform feel and look to improve presentation of portal. But difficult part is when you need to alter these common items.
 

The Tiles framework solve this problem by using templatization mechanism. We create a common Header, Footer, Menu page and include this in each page. A common layout of website is defined in a central configuration file and this layout can be extended across all the web pages of the web application.


Add the following required tiles jars to WEB-INF/lib folder.
  • tiles-api-2.2.2.jar
  • tiles-core-2.2.2.jar
  • tiles-jsp-2.2.2.jar
  • tiles-servlet-2.2.2.jar
  • tiles-template-2.2.2.jar
In the previous chapter we run an application of CRUD operation on the Employee table using Spring3MVC and Hibernate3. Now same we will build same application using tiles configuration (or Tiles View Resolver) as view in stead of JstlView (or JSP View resolver).
Updated view of our application with using the tiles configuration look like as below diagram.
tile structure
Application Structure:
spring3-hibernate-application-architecture-with+tiles

EmployeeBean.java
  1. package com.dineshonjava.bean;  
  2.   
  3. /** 
  4.  * @author Dinesh Rajput 
  5.  * 
  6.  */  
  7. public class EmployeeBean {  
  8.  private Integer id;  
  9.  private String name;  
  10.  private Integer age;  
  11.  private Long salary;  
  12.  private String address;  
  13.    
  14.  public Long getSalary() {  
  15.   return salary;  
  16.  }  
  17.  public void setSalary(Long salary) {  
  18.   this.salary = salary;  
  19.  }  
  20.  public Integer getId() {  
  21.   return id;  
  22.  }  
  23.  public void setId(Integer id) {  
  24.   this.id = id;  
  25.  }  
  26.  public String getName() {  
  27.   return name;  
  28.  }  
  29.  public void setName(String name) {  
  30.   this.name = name;  
  31.  }  
  32.  public Integer getAge() {  
  33.   return age;  
  34.  }  
  35.  public void setAge(Integer age) {  
  36.   this.age = age;  
  37.  }  
  38.  public String getAddress() {  
  39.   return address;  
  40.  }  
  41.  public void setAddress(String address) {  
  42.   this.address = address;  
  43.  }  
  44. }  
Employee.java
  1. package com.dineshonjava.model;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. import javax.persistence.Column;  
  6. import javax.persistence.Entity;  
  7. import javax.persistence.GeneratedValue;  
  8. import javax.persistence.GenerationType;  
  9. import javax.persistence.Id;  
  10. import javax.persistence.Table;  
  11.   
  12. /** 
  13.  * @author Dinesh Rajput 
  14.  * 
  15.  */  
  16. @Entity  
  17. @Table(name="Employee")  
  18. public class Employee implements Serializable{  
  19.   
  20.  private static final long serialVersionUID = -723583058586873479L;  
  21.    
  22.  @Id  
  23.  @GeneratedValue(strategy=GenerationType.AUTO)  
  24.  @Column(name = "empid")  
  25.  private Integer empId;  
  26.    
  27.  @Column(name="empname")  
  28.  private String empName;  
  29.    
  30.  @Column(name="empaddress")  
  31.  private String empAddress;  
  32.    
  33.  @Column(name="salary")  
  34.  private Long salary;  
  35.    
  36.  @Column(name="empAge")  
  37.  private Integer empAge;  
  38.   
  39.  public Integer getEmpId() {  
  40.   return empId;  
  41.  }  
  42.   
  43.  public void setEmpId(Integer empId) {  
  44.   this.empId = empId;  
  45.  }  
  46.   
  47.  public String getEmpName() {  
  48.   return empName;  
  49.  }  
  50.   
  51.  public void setEmpName(String empName) {  
  52.   this.empName = empName;  
  53.  }  
  54.   
  55.  public String getEmpAddress() {  
  56.   return empAddress;  
  57.  }  
  58.   
  59.  public void setEmpAddress(String empAddress) {  
  60.   this.empAddress = empAddress;  
  61.  }  
  62.   
  63.  public Long getSalary() {  
  64.   return salary;  
  65.  }  
  66.   
  67.  public void setSalary(Long salary) {  
  68.   this.salary = salary;  
  69.  }  
  70.   
  71.  public Integer getEmpAge() {  
  72.   return empAge;  
  73.  }  
  74.   
  75.  public void setEmpAge(Integer empAge) {  
  76.   this.empAge = empAge;  
  77.  }  
  78. }  
EmployeeDao.java
  1. package com.dineshonjava.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.dineshonjava.model.Employee;  
  6.   
  7. /** 
  8.  * @author Dinesh Rajput 
  9.  * 
  10.  */  
  11. public interface EmployeeDao {  
  12.    
  13.  public void addEmployee(Employee employee);  
  14.   
  15.  public List<Employee> listEmployeess();  
  16.    
  17.  public Employee getEmployee(int empid);  
  18.    
  19.  public void deleteEmployee(Employee employee);  
  20. }  
EmployeeDaoImpl.java
  1. package com.dineshonjava.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.hibernate.SessionFactory;  
  6. import org.springframework.beans.factory.annotation.Autowired;  
  7. import org.springframework.stereotype.Repository;  
  8.   
  9. import com.dineshonjava.model.Employee;  
  10.   
  11. /** 
  12.  * @author Dinesh Rajput 
  13.  * 
  14.  */  
  15. @Repository("employeeDao")  
  16. public class EmployeeDaoImpl implements EmployeeDao {  
  17.   
  18.  @Autowired  
  19.  private SessionFactory sessionFactory;  
  20.    
  21.  public void addEmployee(Employee employee) {  
  22.    sessionFactory.getCurrentSession().saveOrUpdate(employee);  
  23.  }  
  24.   
  25.  @SuppressWarnings("unchecked")  
  26.  public List<Employee> listEmployeess() {  
  27.   return (List<Employee>) sessionFactory.getCurrentSession().createCriteria(Employee.class).list();  
  28.  }  
  29.   
  30.  public Employee getEmployee(int empid) {  
  31.   return (Employee) sessionFactory.getCurrentSession().get(Employee.class, empid);  
  32.  }  
  33.   
  34.  public void deleteEmployee(Employee employee) {  
  35.   sessionFactory.getCurrentSession().createQuery("DELETE FROM Employee WHERE empid = "+employee.getEmpId()).executeUpdate();  
  36.  }  
  37. }<span style="color: #4c1130;"><b>  
  38. </b></span>  
EmployeeService.java
  1. package com.dineshonjava.service;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.dineshonjava.model.Employee;  
  6.   
  7. /** 
  8.  * @author Dinesh Rajput 
  9.  * 
  10.  */  
  11. public interface EmployeeService {  
  12.    
  13.  public void addEmployee(Employee employee);  
  14.   
  15.  public List<Employee> listEmployeess();  
  16.    
  17.  public Employee getEmployee(int empid);  
  18.    
  19.  public void deleteEmployee(Employee employee);  
  20. }  
EmployeeServiceImpl.java
  1. package com.dineshonjava.service;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.stereotype.Service;  
  7. import org.springframework.transaction.annotation.Propagation;  
  8. import org.springframework.transaction.annotation.Transactional;  
  9.   
  10. import com.dineshonjava.dao.EmployeeDao;  
  11. import com.dineshonjava.model.Employee;  
  12.   
  13. /** 
  14.  * @author Dinesh Rajput 
  15.  * 
  16.  */  
  17. @Service("employeeService")  
  18. @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)  
  19. public class EmployeeServiceImpl implements EmployeeService {  
  20.   
  21.  @Autowired  
  22.  private EmployeeDao employeeDao;  
  23.    
  24.  @Transactional(propagation = Propagation.REQUIRED, readOnly = false)  
  25.  public void addEmployee(Employee employee) {  
  26.   employeeDao.addEmployee(employee);  
  27.  }  
  28.    
  29.  public List<Employee> listEmployeess() {  
  30.   return employeeDao.listEmployeess();  
  31.  }  
  32.   
  33.  public Employee getEmployee(int empid) {  
  34.   return employeeDao.getEmployee(empid);  
  35.  }  
  36.    
  37.  public void deleteEmployee(Employee employee) {  
  38.   employeeDao.deleteEmployee(employee);  
  39.  }  
  40.   
  41. }  
EmployeeController.java
  1. package com.dineshonjava.controller;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. import org.springframework.beans.factory.annotation.Autowired;  
  9. import org.springframework.stereotype.Controller;  
  10. import org.springframework.validation.BindingResult;  
  11. import org.springframework.web.bind.annotation.ModelAttribute;  
  12. import org.springframework.web.bind.annotation.RequestMapping;  
  13. import org.springframework.web.bind.annotation.RequestMethod;  
  14. import org.springframework.web.servlet.ModelAndView;  
  15.   
  16. import com.dineshonjava.bean.EmployeeBean;  
  17. import com.dineshonjava.model.Employee;  
  18. import com.dineshonjava.service.EmployeeService;  
  19.   
  20. /** 
  21.  * @author Dinesh Rajput 
  22.  * 
  23.  */  
  24. @Controller  
  25. public class EmployeeController {  
  26.    
  27.  @Autowired  
  28.  private EmployeeService employeeService;  
  29.    
  30. @RequestMapping(value = "/save", method = RequestMethod.POST)  
  31. public ModelAndView saveEmployee(@ModelAttribute("command")EmployeeBean employeeBean,   
  32.    BindingResult result) {  
  33.   Employee employee = prepareModel(employeeBean);  
  34.   employeeService.addEmployee(employee);  
  35.   return new ModelAndView("redirect:/add.html");  
  36.  }  
  37.   
  38.  @RequestMapping(value="/employees", method = RequestMethod.GET)  
  39.  public ModelAndView listEmployees() {  
  40.   Map<String, Object> model = new HashMap<String, Object>();  
  41.   model.put("employees",  prepareListofBean(employeeService.listEmployeess()));  
  42.   return new ModelAndView("employeesList", model);  
  43.  }  
  44.   
  45.  @RequestMapping(value = "/add", method = RequestMethod.GET)  
  46.  public ModelAndView addEmployee(@ModelAttribute("command")EmployeeBean employeeBean,  
  47.    BindingResult result) {  
  48.   Map<String, Object> model = new HashMap<String, Object>();  
  49.   model.put("employees",  prepareListofBean(employeeService.listEmployeess()));  
  50.   return new ModelAndView("addEmployee", model);  
  51.  }  
  52.    
  53. @RequestMapping(value = "/index", method = RequestMethod.GET)  
  54. public ModelAndView welcome() {  
  55.   return new ModelAndView("redirect:/add.html");  
  56.  }  
  57.   
  58. @RequestMapping(value = "/delete", method = RequestMethod.GET)  
  59. public ModelAndView editEmployee(@ModelAttribute("command")EmployeeBean employeeBean,  
  60.    BindingResult result) {  
  61.   employeeService.deleteEmployee(prepareModel(employeeBean));  
  62.   Map<String, Object> model = new HashMap<String, Object>();  
  63.   model.put("employee"null);  
  64.   model.put("employees",  prepareListofBean(employeeService.listEmployeess()));  
  65.   return new ModelAndView("addEmployee", model);  
  66.  }  
  67.    
  68. @RequestMapping(value = "/edit", method = RequestMethod.GET)  
  69. public ModelAndView deleteEmployee(@ModelAttribute("command")EmployeeBean employeeBean,  
  70.    BindingResult result) {  
  71.   Map<String, Object> model = new HashMap<String, Object>();  
  72.   model.put("employee", prepareEmployeeBean(employeeService.getEmployee(employeeBean.getId())));  
  73.   model.put("employees",  prepareListofBean(employeeService.listEmployeess()));  
  74.   return new ModelAndView("addEmployee", model);  
  75.  }  
  76.    
  77.  private Employee prepareModel(EmployeeBean employeeBean){  
  78.   Employee employee = new Employee();  
  79.   employee.setEmpAddress(employeeBean.getAddress());  
  80.   employee.setEmpAge(employeeBean.getAge());  
  81.   employee.setEmpName(employeeBean.getName());  
  82.   employee.setSalary(employeeBean.getSalary());  
  83.   employee.setEmpId(employeeBean.getId());  
  84.   employeeBean.setId(null);  
  85.   return employee;  
  86.  }  
  87.    
  88.  private List<EmployeeBean> prepareListofBean(List<Employee> employees){  
  89.   List<employeebean> beans = null;  
  90.   if(employees != null && !employees.isEmpty()){  
  91.    beans = new ArrayList<EmployeeBean>();  
  92.    EmployeeBean bean = null;  
  93.    for(Employee employee : employees){  
  94.     bean = new EmployeeBean();  
  95.     bean.setName(employee.getEmpName());  
  96.     bean.setId(employee.getEmpId());  
  97.     bean.setAddress(employee.getEmpAddress());  
  98.     bean.setSalary(employee.getSalary());  
  99.     bean.setAge(employee.getEmpAge());  
  100.     beans.add(bean);  
  101.    }  
  102.   }  
  103.   return beans;  
  104.  }  
  105.    
  106.  private EmployeeBean prepareEmployeeBean(Employee employee){  
  107.   EmployeeBean bean = new EmployeeBean();  
  108.   bean.setAddress(employee.getEmpAddress());  
  109.   bean.setAge(employee.getEmpAge());  
  110.   bean.setName(employee.getEmpName());  
  111.   bean.setSalary(employee.getSalary());  
  112.   bean.setId(employee.getEmpId());  
  113.   return bean;  
  114.  }  
  115. }  
Spring Web configuration file web.xml
<web-app version="2.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemalocation="http://java.sun.com/xml/ns/javaee 
          http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

   <servlet>
     <servlet-name>sdnext</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <init-param>
            <param-name>contextConfigLocation</param-name><param-value>/WEB-INF/config/sdnext-servlet.xml</param-value></init-param>
     <load-on-startup>1</load-on-startup>
   </servlet>

 <servlet-mapping>
  <servlet-name>sdnext</servlet-name>
  <url-pattern>*.html</url-pattern>
 </servlet-mapping>

 <welcome-file-list>
  <welcome-file>index.html</welcome-file>
 </welcome-file-list>

</web-app>

Spring Web configuration file sdnext-servlet.xml
<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" 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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<context:property-placeholder location="classpath:resources/database.properties">
</context:property-placeholder>
<context:component-scan base-package="com.dineshonjava">
</context:component-scan>

<tx:annotation-driven transaction-manager="hibernateTransactionManager">
</tx:annotation-driven>

<!-- <bean id="jspViewResolver"
 class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 <property name="viewClass"
  value="org.springframework.web.servlet.view.JstlView"></property>
 <property name="prefix" value="/WEB-INF/views/"></property>
 <property name="suffix" value=".jsp"></property>
</bean> -->
 
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="viewResolver">
    <property name="viewClass">
 <value>
     org.springframework.web.servlet.view.tiles2.TilesView
 </value>
     </property>
</bean>
<bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer" id="tilesConfigurer">
    <property name="definitions">
  <list>
      <value>/WEB-INF/config/tiles.xml</value>
  </list>
      </property>
</bean>

<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
 <property name="driverClassName" value="${database.driver}"></property>
 <property name="url" value="${database.url}"></property>
 <property name="username" value="${database.user}"></property>
 <property name="password" value="${database.password}"></property>
</bean>

<bean class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" id="sessionFactory">
 <property name="dataSource" ref="dataSource"></property>
 <property name="annotatedClasses">
  <list>
   <value>com.dineshonjava.model.Employee</value>
  </list>
 </property>
 <property name="hibernateProperties">
 <props>
  <prop key="hibernate.dialect">${hibernate.dialect}</prop>
  <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
  <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}  </prop>    
        </props>
      </property>
</bean>

  <bean class="org.springframework.orm.hibernate3.HibernateTransactionManager" id="hibernateTransactionManager">
 <property name="sessionFactory" ref="sessionFactory"></property>
  </bean>
</beans>
tiles.xml
<tiles-definitions>
    <definition name="base.definition" template="/WEB-INF/views/mainTemplate.jsp">
        <put-attribute name="title" value=""></put-attribute>
        <put-attribute name="header" value="/WEB-INF/views/header.jsp"></put-attribute>
        <put-attribute name="menu" value="/WEB-INF/views/menu.jsp"></put-attribute>
        <put-attribute name="body" value=""></put-attribute>
        <put-attribute name="footer" value="/WEB-INF/views/footer.jsp"></put-attribute>
    </definition>
 
    <definition extends="base.definition" name="addEmployee">
        <put-attribute name="title" value="Employee Data Form"></put-attribute>
        <put-attribute name="body" value="/WEB-INF/views/addEmployee.jsp"></put-attribute>
    </definition>
    
    <definition extends="base.definition" name="employeesList">
        <put-attribute name="title" value="Employees List"></put-attribute>
        <put-attribute name="body" value="/WEB-INF/views/employeesList.jsp"></put-attribute>
    </definition>
 
</tiles-definitions>
database.properties
database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/DAVDB
database.user=root
database.password=root
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
addEmployee.jsp
  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
  2.     pageEncoding="ISO-8859-1"%>  
  3. <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>  
  4. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
  5.   
  6. <html>  
  7.  <head>  
  8.     
  9.   <title>Spring MVC Form Handling</title>  
  10.  </head>  
  11.  <body>  
  12.   <h2>Add Employee Data</h2>  
  13. <form:form action="/sdnext/save.html" method="POST">       
  14.   <table>
  15.    <tbody>  
  16.       <tr>          
  17.         <td><form:label path="id">Employee ID:</form:label></td>
  18.           <td><form:input path="id" readonly="true" value="${employee.id}"> 
  19.           </form:input></td>
  20.       </tr>  
  21.       <tr>  
  22.          <td><form:label path="name">Employee Name:</form:label></td> 
  23.         <td><form:input path="name" value="${employee.name}">   
  24.          </form:input></td> 
  25.      </tr>  
  26.      <tr>
  27.        <td><form:label path="age">Employee Age:</form:label></td> 
  28.        <td><form:input path="age" value="${employee.age}">
  29.        </form:input></td> 
  30.      </tr>  
  31.      <tr> 
  32.         <td><form:label path="salary">Employee Salary:</form:label></td> 
  33.         <td><form:input path="salary" value="${employee.salary}">
  34.          </form:input></td>
  35.      </tr>  
  36.      <tr> 
  37.         <td><form:label path="address">Employee Address:</form:label></td> 
  38.         <td><form:input path="address" value="${employee.address}">
  39.          </form:input></td> 
  40.      </tr>  
  41.     <tr> 
  42.         <td colspan="2"> 
  43.           <input type="submit" value="Submit"></td> 
  44.      </tr>  
  45.    </tbody> 
  46.   </table>  
  47. </form:form>    
  48.   <c:if test="${!empty employees}">  
  49.    <h2>  List Employees</h2>  
  50.  <table align="left" border="1"> 
  51.    <tbody> 
  52.      <tr> 
  53.         <th>Employee ID</th> 
  54.         <th>Employee Name</th> 
  55.         <th>Employee Age</th>
  56.         <th>Employee Salary</th> 
  57.         <th>Employee Address</th> 
  58.         <th>Actions on Row</th> 
  59.    </tr>  
  60. <c:foreach items="${employees}" var="employee">
  61.  <tr> 
  62.     <td><c:out value="${employee.id}"></c:out> 
  63. </td>
  64.       <td><c:out value="${employee.name}"></c:out>
  65.  </td> 
  66.      <td><c:out value="${employee.age}"></c:out>
  67.  </td>
  68.       <td><c:out value="${employee.salary}"></c:out> 
  69. </td> 
  70.      <td><c:out value="${employee.address}"></c:out>
  71.  </td>
  72.       <td align="center"><a href="edit.html/?id=${employee.id}">Edit</a> |  
  73.      <a href="delete.html/?id=${employee.id}">Delete</a> 
  74.    </td> 
  75.    </tr> 
  76. </c:foreach>
  77.  
  78. </tbody></table>  
  79. </c:if>  
  80.  </body>  
  81. </html>  
employeesList.jsp
  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
  2.     pageEncoding="ISO-8859-1"%>  
  3. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
  4.   
  5. <html>  
  6. <head>  
  7. <title>All Employees</title>  
  8. </head>  
  9. <body>  
  10. <h1>  
  11. List Employees</h1>  
  12. <h3>  
  13. <a href="http://add.html/">Add More Employee</a></h3>  
  14. <c:if test="${!empty employees}">  
  15.  
  16. <table align="left" border="1"> 
  17. <tbody>  
  18. <tr> 
  19.     <th>Employee ID</th> 
  20.     <th>Employee Name</th> 
  21.     <th>Employee Age</th> 
  22.     <th>Employee Salary</th> 
  23.     <th>Employee Address</th>
  24.     </tr>  
  25. <c:foreach items="${employees}" var="employee"> 
  26. <tr> 
  27.      <td><c:out value="${employee.id}"></c:out>
  28.  </td> 
  29.      <td><c:out value="${employee.name}"></c:out> 
  30. </td> 
  31.      <td><c:out value="${employee.age}"></c:out> 
  32. </td>
  33.       <td><c:out value="${employee.salary}"></c:out> 
  34. </td> 
  35.      <td><c:out value="${employee.address}"></c:out></td> 
  36.   </tr>  
  37. </c:foreach>
  38. </tbody>
  39.  </table>  
  40. </c:if>  
  41. </body>  
  42. </html>  
menu.jsp
  1.   <h2>  Menu</h2>  
  2. 1. <a href="employees.html">List of Employees</a> 
  3. 2. <a href="add.html">Add Employee</a>
header.jsp
  1. <h2>Header- Employee Management System</h2>
footer.jsp
  1.  
  2.     <p>Copyright &copy; 2013 dineshonjava.com</p> 
mainTemplate.jsp
  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
  2.     pageEncoding="ISO-8859-1"%>  
  3.   
  4. <html>  
  5.   <head>  
  6.       
  7.     <title>
        <tiles:insertAttribute name="title" ignore="true"></tiles:insertAttribute>
    </title>
    </head>
    <body>
    <table border="1" cellpadding="2" cellspacing="2" align="left">
        <tr>
            <td colspan="2" align="center">
                <tiles:insertAttribute name="header"></tiles:insertAttribute>
            </td>
        </tr>
        <tr>
            <td>
                <tiles:insertAttribute name="menu"></tiles:insertAttribute>
            </td>
            <td>
                <tiles:insertAttribute name="body"></tiles:insertAttribute>
            </td>
        </tr>
        <tr>
            <td colspan="2"  align="center">
                <tiles:insertAttribute name="footer"></tiles:insertAttribute>
            </td>
        </tr>
    </table>
  8. </body>  
  9. </html>

tilesapp
Once you are done with creating source and configuration files, export your application. Right click on your application and use Export-> WAR File option and save your Spring3TilesApp.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 a URL http://localhost:8080/sdnext/ and you should see the following result if everything is fine with your Spring Web Application:

tileoutput

Now we click on the List of Employee link on the Menu section then we get the following output screen we observe that only body of the mainTemplate is refreshed.

tileoutput2

Dwonload this Application SourceCode+Libs

Spring3TilesApp.zip


   <<Spring Web MVC Framework |index| Spring 3 MVC Framework with Interceptor>>