Spring MVC Tiles 3 Integration Tutorial

2017.01.15 14:17

졸리운_곰 조회 수:173

Spring MVC Tiles 3 Integration Tutorial

In this post, I will show how to integrate Apache Tiles 3 with Spring MVC.

Build APIs from SQL and NoSQL or Salesforce data sources in seconds. Read the Creating REST APIs white paper, brought to you in partnership with CA Technologies.

One of the areas in which Spring MVC has advance compares to other frameworks is in the separation of view technologies. In this post, i will show how to integrate Apache Tiles 3 with Spring MVC. Apache Tiles is a free open-source template engine for java web frameworks. It’s based on Composite pattern and used to simplify the development of user interfaces.

Create a spring configuration XML file which add bean definition for TilesConfigurar and TilesView.

 
<?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:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
 
xmlns:mvc="http://www.springframework.org/schema/mvc"
 
xsi:schemaLocation="http://www.springframework.org/schema/beans 
 
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 
http://www.springframework.org/schema/context
 
http://www.springframework.org/schema/context/spring-context-3.2.xsd
 
http://www.springframework.org/schema/mvc
 
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
 
http://www.springframework.org/schema/tx
 
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
 

 
 
<context:annotation-config />
 
<context:component-scan base-package="org.techzoo.springtiles.controller" />
 

 
 
<mvc:annotation-driven />
 
<mvc:default-servlet-handler />
 
<mvc:resources mapping="/resources/**" location="/resources/" />
 

 
 
<bean id="viewResolver" class="org.springframework.web.servlet.view.tiles3.TilesViewResolver"/>
 

 
 
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
 
<property name="definitions">
 
<list>
 
<value>/WEB-INF/layouts/layouts.xml</value>
 
<value>/WEB-INF/layouts/views.xml</value>
 
</list>
 
</property>
 
</bean>
 

 
 
</beans>
 

Now create a tiles definition xml file which contains tiles template definitions. I have created two xml files, one for tiles base template and another for tiles body definition but you can combine it in one.

 
<?xml version="1.0" encoding="UTF-8"?>
 
 <!DOCTYPE tiles-definitions PUBLIC  
 
        "-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN"  
 
        "http://tiles.apache.org/dtds/tiles-config_3_0.dtd">
 
<tiles-definitions>
 

 
 
    <definition name="DefaultTemplate" 
 
      template="/WEB-INF/views/template/SiteTemplate.jsp">
 
<put-attribute name="title" value="Home" />
 
<put-attribute name="header" value="/WEB-INF/views/template/header.jsp" />
 
<put-attribute name="menu" value="/WEB-INF/views/template/menu.jsp" />
 
<put-attribute name="body" value="" />
 
<put-attribute name="footer" value="/WEB-INF/views/template/footer.jsp" />
 
</definition>
 

 
 
</tiles-definitions>
 

Create a template jsp which include the common pages (like header, footer, menu etc.). I have used Blueprint css framework to create a grid for layout.

 
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
 
<html xmlns="http://www.w3.org/1999/xhtml">
 
<head>
 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 
<title>Spring MVC - Tiles Integration tutorial</title>
 
<link rel="stylesheet" href="resources/css/screen.css" 
 
      type="text/css" media="screen, projection"></link>
 
<link rel="stylesheet" href="resources/css/print.css" 
 
      type="text/css" media="print"></link>
 
<!--[if IE]>
 
<link rel="stylesheet" href="resources/css/ie.css" 
 
      type="text/css" media="screen, projection">
 
<![endif]-->
 
<style>
 
body{ margin-top:20px; margin-bottom:20px; background-color:#DFDFDF;}
 
</style>
 
</head>
 
<body>
 
<div class="container" style="border: #C1C1C1 solid 1px; border-radius:10px;">
 
<!-- Header -->
 
<tiles:insertAttribute name="header" />
 
<!-- Menu Page -->
 
<div class="span-5  border" style="height:400px;background-color:#FCFCFC;">
 
<tiles:insertAttribute name="menu" />
 
</div>
 
<!-- Body Page -->
 
<div class="span-19 last">
 
<tiles:insertAttribute name="body" />
 
</div>
 
<!-- Footer Page -->
 
<tiles:insertAttribute name="footer" />
 
</div>
 
</body>
 
</html>
 

Header.jsp

 
<div class="span-24">
 
    <img src="resources/images/techzoo-header.png"
 
        width="950" style="padding-top:10px;" />
 
</div>
 

Footer.jsp

 
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
 
<ul style="list-style:none;line-height:28px;">
 

 
 
    <li>
 
    <spring:url value="/index" var="homeUrl" htmlEscape="true" />
 
        <a href="${homeUrl}">Home</a>
 
    </li>
 

 
 
    <li>
 
    <spring:url value="/viewPeson" var="personListUrl" htmlEscape="true" />
 
        <a href="${personListUrl}">Person List</a>
 
    </li>
 

 
 
</ul>
 

As you can see, In you main template jsp we have inserted body attribute but in tiles-def xml file that body attribute is blank. This is because spring controller will render this portion using its view rendering mechanism.

Create a Controller which has two action (index and viewPeson) . The return value of every controller will be mapped with each tiles definition which is associated with jsp to render as body in template.

 
ackage org.techzoo.springtiles.controller;
 

 
 
import java.util.HashMap;
 
import java.util.List;
 
import java.util.Map;
 

 
 
import org.springframework.stereotype.Controller;
 
import org.springframework.ui.Model;
 
import org.springframework.web.bind.annotation.RequestMapping;
 
import org.springframework.web.servlet.ModelAndView;
 
import org.techzoo.springtiles.vo.Person;
 

 
 
@Controller
 
public class SpringTilesController {
 

 
 
    @RequestMapping(value="index")
 
    public String index() {
 
        return "index";
 
    }
 

 
 
    @RequestMapping(value="viewPeson")
 
    public ModelAndView viewPersons(Model model) {
 
        Map<String, List<Person>> persons =
 
                new HashMap<String, List<Person>>();
 
        persons.put("persons", Person.createPersons());
 
        return new ModelAndView("personList", persons);
 
    }
 

 
 
}
 

A Person VO class just to show a list of person in personList.jsp.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

 
ckage org.techzoo.springtiles.vo;
 

 
 
import java.util.ArrayList;
 
import java.util.List;
 

 
 
public class Person {
 

 
 
    private String name, email;
 
    private int age;
 

 
 
    public Person(String name, String email, int age) {
 
        this.name = name;
 
        this.email = email;
 
        this.age = age;
 
    }
 

 
 
    //getter, setters methods
 

 
 
    @Override
 
    public String toString()
 
    {
 
        return String.format(
 
            "Person [name = %s, email = %s, age = %d]",
 
                name, email, age);
 
    }
 

 
 
    public static List<Person> createPersons() {
 
        List<Person> persons = new ArrayList<Person>();
 
        persons.add(new Person("Tousif", "tousif@mail.com", 32));
 
        persons.add(new Person("Asif", "asif@mail.com", 28));
 
        persons.add(new Person("Ramiz", "ramiz@mail.com", 26));
 
        persons.add(new Person("Rizwan", "rizwan@mail.com", 32));
 
        persons.add(new Person("Amol", "amol@mail.com", 33));
 
        persons.add(new Person("Ramdas", "ramdas@mail.com", 31));
 
        return persons;
 
    }
 
}
 

Your second tiles defination xml (views.xml) will looks similar to following. Both the tile defination ‘index’ and ‘personList’ is extending ‘DefaultTemplate’.

 
<?xml version="1.0" encoding="UTF-8"?>
 
<!DOCTYPE tiles-definitions PUBLIC
 
"-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN"
 
"http://tiles.apache.org/dtds/tiles-config_3_0.dtd">
 
<tiles-definitions>
 

 
 
<definition name="index" extends="DefaultTemplate">
 
    <put-attribute name="body"
 
        value="/WEB-INF/views/index.jsp" />
 
</definition>
 

 
 
<definition name="personList" extends="DefaultTemplate">
 
    <put-attribute name="body"
 
        value="/WEB-INF/views/personList.jsp" />
 
</definition>
 

 
 
</tiles-definitions>
 

index.jsp

 
<div style="margin:10px;">
 
<h3>SpringMVC - Tiles3 Integration tutorial</h3>
 
<p>By:- Tousif Khan</p>
 
</div>
 

personList.jsp

 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 
<div style="margin: 10px;">
 
<h4>List of Persons</h4>
 
<table style="width: 600px" class="reference">
 
<tbody>
 
<tr>
 
<th>Sr. No.</th>
 
<th>Name</th>
 
<th>Age</th>
 
<th>Email</th>
 
</tr>
 
<c:forEach var="person" items="${requestScope.persons}"
 
varStatus="loopCounter">
 
<tr>
 
<td><c:out value="${loopCounter.count}" /></td>
 
<td><c:out value="${person.name}" /></td>
 
<td><c:out value="${person.email}" /></td>
 
<td><c:out value="${person.age}" /></td>
 
</tr>
 
</c:forEach>
 
</tbody>
 
</table>
 
</div>
 

 

Output:

[출처] https://dzone.com/articles/spring-mvc-tiles-3-integration

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
26 [bootstrap] spring 프로젝트에 bootstrap 적용 file 졸리운_곰 2017.01.29 164
25 eGov 표준프레임워크(전자정부프레임워크) 공통 컴포넌트 사용법 : Common Component file 졸리운_곰 2017.01.29 1030
24 Passing Javascript object and object list to Spring controller 졸리운_곰 2017.01.23 92
23 뷰에 모델(Model) 전달 file 졸리운_곰 2017.01.22 128
22 CentOS에서 Apache Tomcat 설치하기 졸리운_곰 2017.01.18 490
21 Spring MVC Tiles Plugin with Example file 졸리운_곰 2017.01.15 1384
» Spring MVC Tiles 3 Integration Tutorial file 졸리운_곰 2017.01.15 173
19 Spring 3 MVC: Tiles Plugin Tutorial with Example in Eclipse file 졸리운_곰 2017.01.15 194
18 MyBatis 에서 한 insert 태그로 여러 Insert문 수행 졸리운_곰 2016.12.09 112
17 Web App Architecture - the Spring MVC - AngularJs stack file 졸리운_곰 2016.11.20 208
16 Introduction to Angular 2 with Spring MVC file 졸리운_곰 2016.11.20 676
15 Migrating a Spring Web MVC application from JSP to AngularJS file 졸리운_곰 2016.11.20 114
14 스프링(Spring) MVC 프레임워크(Model View Controller Framework) file 졸리운_곰 2016.11.16 151
13 JSP 정리 졸리운_곰 2016.09.11 332
12 JSP 요약 정리 file 졸리운_곰 2016.09.11 1294
11 전자정부 eGov 프레임워크 모바일 실행환경 Upgrade 가이드 file 졸리운_곰 2016.08.02 327
10 전자정부 eGov 프레임워크 개발프레임워크 개발환경 졸리운_곰 2016.08.02 474
9 표준프레임워크 실행환경 3.5 졸리운_곰 2016.08.02 172
8 전자정부 표준프레임워크 3.5 기반 개발 시작하기(Getting Started) file 졸리운_곰 2016.08.02 291
7 스프링(Spring) MVC 프레임워크(Model View Controller Framework) file 졸리운_곰 2016.07.31 103
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED