Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java EE (J2EE) и Spring > помогите разобраться с Tiles


Автор: drdoom 31.1.2008, 10:46
Вообщем мне надо понять что представляет из себя Tiles, желательно с примерами применения, или ссылки на ресурсы с примерам, заранее спасибо

Автор: Tigra 2.2.2008, 16:49
Framework Tiles используется для  уменьшения повторений кода jsp-страниц и позволяет делать страницы более гибкими.
Tiles – прямоугольная область web-страницы.
Вот самы простой пример:
1. Создаем страницу layout.jsp, на которой используются tiles:
Код

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<table width="100%" height="100%">
<tr height="20%">
   <td colspan="2" align="center" bgcolor="#b9b9ff">
       <tiles:insert attribute="header" />
   </td>
</tr>
<tr>
    <td width="30%" align="center" bgcolor="#ffc1ff">
         <tiles:insert attribute="menu" />
    </td>
    <td width="70%" align="center" bgcolor="#c6ffff">
         <tiles:insert attribute="content" />
    </td>
</tr>
<tr height="20%">
    <td colspan="2" align="center" bgcolor="#ffffb9">
         <tiles:insert attribute="footer" />
    </td>
</tr>
</table>
</body></html>

2. Создаем четыре jsp-страницы: header.jsp, footer.jsp, menu.jsp, content.jsp.
header.jsp:
Код

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

menu.jsp:
Код

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

content.jsp:
Код

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

footer.jsp:
Код

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

3. В WEB-INF создаем файл tiles-defs.xml, в котором описываем использование tiles на страницах проекта:
Код

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

<tiles-definitions>

  <definition name="mainPage" path="/layout.jsp">
    <put name="header" value="/header.jsp"  />
    <put name="footer" value="/footer.jsp"  />
    <put name="menu" value="/menu.jsp"  />
    <put name="content" value="/content.jsp"  />
  </definition>
  
</tiles-definitions>

4. В struts-config.xml добавим:
Код

<?xml version="1.0" encoding="UTF-8"?>
<struts-config>

    <action-mappings>
        <action
            path="/InputSubmit"
            forward="mainPage"
         />
    </action-mappings>

    <plug-in className="org.apache.struts.tiles.TilesPlugin">
        <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml"/>
    </plug-in>

</struts-config>

5. web.xml :
Код

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Tiles</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
    <servlet>
      <servlet-name>action</servlet-name>
      <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
      <init-param>
        <param-name>config</param-name>
        <param-value>/WEB-INF/struts-config.xml</param-value>
      </init-param>
      
      <init-param>
       <param-name>chainConfig</param-name>
       <param-value> <!-- 1.3.x   1.2.9 -->
           org/apache/struts/tiles/chain-config.xml
       </param-value>
      </init-param>

      <load-on-startup>2</load-on-startup>
   </servlet>
 
    <!-- Standard Action Servlet Mapping -->
    <servlet-mapping>
      <servlet-name>action</servlet-name>
      <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

6. Вызываем страницу http://localhost:8080/Tiles/InputSubmit.do 

Автор: drdoom 4.2.2008, 09:48
Спасиб большое разобрался

Автор: Tamerlann 4.2.2008, 12:00
Я раньше тоже не сталкивался с Tiles, и у меня тоже есть встречный вопрос - а чем это отличается от 

Код

<%@ include file="/header.html" %>


?

Тем болле что Tiles, как видно, требует большого числа вспомогательных операций (tiles-defs.xml и проч.), в то время как стандартный include JSP работает и без этого. 

Иначе говоря вопрос вот в чем: в чем приемущество использования Tiles?

Автор: Kangaroo 4.2.2008, 12:13
Цитата(Tamerlann @  4.2.2008,  11:00 Найти цитируемый пост)
Иначе говоря вопрос вот в чем: в чем приемущество использования Tiles? 

Вот недавно встретил http://www.velocityreviews.com/forums/t303509-what-is-the-main-advantage-of-using-tiles-framework.html:
Цитата

I am a big believer in the Tiles framework. It's main advantage, in my
viewpoint, is its ability to increase reuse across the presentation
tier of an application.

With Tiles a developer can set up a few Tile definitions (templates)
that represent the different page layouts across a web app. Each Tile
definition can have both concrete JSPs as well as empty Tiles. Then,
through Tile inheritence, each template can be extended n times to
create any number of pages. Say that a web app has a common header and
footer across 10 pages. Tiles allows the developer to create one JSP
for the header, one JSP for the footer, one Tile definition, and 10
JSPs for the body of each page. If the header JSP changes the change
ripples through all pages without any need to change the Tiles XML.

Sure, you could use jsp:include and get a similar result but you would
lose the flexibility of the XML configuration and the inheritence that
Tiles provides you. In the near term it will save development time
with each new page that you create that fits into one of the templates
you have defined. In the long run it will make the application much
easier to maintain.


PS
2Модераторы
Может добавить это в FAQ? Хоть текста там немного, но хоть какой-нибудь пример.

Добавлено через 37 секунд
Под "это" я имел ввиду пост Tigra  smile 

Автор: drdoom 4.2.2008, 12:19
всем спасибо

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)