My linux world » Java Spring – Tiles

Java Spring - Tiles


Contents

Prerequistes

Please read : Java spring – quickstart

Configuration

WebMvcConfig.java

Set the following beans :

  @Bean
  public UrlBasedViewResolver viewResolver() {    
    UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();    
    viewResolver.setViewClass(TilesView.class);
    viewResolver.setOrder(1);
    return viewResolver;
  }  
 
  @Bean
  public TilesConfigurer tilesConfigurer() {
    TilesConfigurer tilesConfigurer = new TilesConfigurer();
    tilesConfigurer.setDefinitions("/WEB-INF/tiles.xml");
    return tilesConfigurer;
  }

tiles.xml

Create src/main/webapp/WEB-INF/tiles.xml file :

<?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>
 
    <!-- Parent -->
    <definition name="tiles.template" template="/WEB-INF/jsp/template/template.jsp" >
		<put-attribute name="header" value="/WEB-INF/jsp/template/header.jsp" />
		<put-attribute name="footer" value="/WEB-INF/jsp/template/footer.jsp" />
	</definition>
 
	<!-- Child -->
	<definition name="/*/*" extends="tiles.template">
		<put-attribute name="content" value="/WEB-INF/jsp/pages/{1}/{2}.jsp" />
	</definition>
 
</tiles-definitions>

This mean that all url “/A/B” will use the jsp : /WEB-INF/jsp/pages/A/B.jsp as “content” attribute.

template

template.jsp will insert the defined attributes (see tiles.xml) :

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
 
<!DOCTYPE html>
 
<html>
  <head>
 
  </head>
 
  <body>
 
    <tiles:insertAttribute name="header" />
    <tiles:insertAttribute name="content" />
    <tiles:insertAttribute name="footer" />
  </body>
</html>

header.jsp :

<h2>Header</h2>

footer.jsp :

<h2>Footer</h2>

Copyright © 2024 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.