openplanning

Hướng dẫn sử dụng Spring Boot, Apache Tiles, JSP

Xem thêm các chuyên mục:

Nhóm phát triển của chúng tôi vừa ra mắt website langlearning.net học tiếng Anh, Nga, Đức, Pháp, Việt, Trung, Hàn, Nhật, ... miễn phí cho tất cả mọi người.
Là một website được viết trên công nghệ web Flutter vì vậy hỗ trợ rất tốt cho người học, kể cả những người học khó tính nhất.
Hiện tại website đang tiếp tục được cập nhập nội dung cho phong phú và đầy đủ hơn. Mong các bạn nghé thăm và ủng hộ website mới của chúng tôi.
Hãy theo dõi chúng tôi trên Fanpage để nhận được thông báo mỗi khi có bài viết mới. Facebook

1- Apache Tiles là gì?

Apache Titles lấy lý tưởng từ việc xếp các viên ngói lại với nhau để tạo nên mái nhà.
Một trang web (web page) của bạn được coi là một mái nhà, nó được ghép lại từ các viên ngói, một viên ngói ở đây là một tập tin jsp (Trong tình huống này nó cũng được gọi là một mảnh - fragment). Apache Titles giúp bạn định nghĩa ra một khuôn mẫu (Template) để ghép các thành phần (các mảnh) lại với nhau để thành một trang hoàn chỉnh.
 
Apache Tiles dựa trên mô hình Composite nó được xây dựng để đơn giản hóa sự phát triển cho giao diện người dùng. Hãy thử tưởng tượng ứng dụng web của bạn có nhiều trang, nhưng thực ra chúng có cấu trúc giống nhau. Đơn giản nhất là một cấu trúc cổ điển bao gồm 4 phần Header, Footer, Menu, Body. Thay vì bạn thiết kế một trang theo một khối, bạn hãy thiết kế theo nhiều thành phần và ghép lại với nhau.

2- Mục tiêu của ví dụ

Trong bài viết này tôi hướng dẫn bạn tạo một ứng dụng Spring Boot, thiết kế các thành phần của giao diện bằng JSP, và sử dụng Apache Tiles để lắp ghép các thành phần giao diện lại với nhau thành một trang hoàn chỉnh.

3- Tạo dự án Spring Boot

Nhập vào:
  • Name: SpringBootJspTiles
  • Group: org.o7planning
  • Artifact: SpringBootJspTiles
  • Description: Spring Boot + Apache Tiles + JSP
  • Package: org.o7planning.sbtiles
SpringBootJspTilesApplication.java

package org.o7planning.sbtiles;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootJspTilesApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootJspTilesApplication.class, args);
    }
    
}

4- Cấu hình pom.xml

Khai báo thư viện cần thiết cho JSP/ServletApache Tiles vào tập tin pom.xml.
JSP/Servlet + Tiles

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
</dependency>

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
</dependency>

<!-- Tiles API -->
<!-- http://mvnrepository.com/artifact/org.apache.tiles/tiles-api -->
<dependency>
    <groupId>org.apache.tiles</groupId>
    <artifactId>tiles-api</artifactId>
    <version>3.0.8</version>
</dependency>


<!-- Tiles Core -->
<!-- http://mvnrepository.com/artifact/org.apache.tiles/tiles-core -->
<dependency>
    <groupId>org.apache.tiles</groupId>
    <artifactId>tiles-core</artifactId>
    <version>3.0.8</version>
</dependency>

<!-- Tiles Servlet -->
<!-- http://mvnrepository.com/artifact/org.apache.tiles/tiles-servlet -->
<dependency>
    <groupId>org.apache.tiles</groupId>
    <artifactId>tiles-servlet</artifactId>
    <version>3.0.8</version>
</dependency>

<!-- Tiles JSP -->
<!-- http://mvnrepository.com/artifact/org.apache.tiles/tiles-jsp -->
<dependency>
    <groupId>org.apache.tiles</groupId>
    <artifactId>tiles-jsp</artifactId>
    <version>3.0.8</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.tiles/tiles-request-api -->
<dependency>
    <groupId>org.apache.tiles</groupId>
    <artifactId>tiles-request-api</artifactId>
    <version>1.0.6</version>
</dependency>
Nội dung đầy đủ của tập tin pom.xml:
pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
       http://maven.apache.org/xsd/maven-4.0.0.xsd">
       
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.o7planning</groupId>
    <artifactId>SpringBootJspTiles</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>SpringBootJspTiles</name>
    <description>Spring Boot + JSP + Apache Tiles</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>



    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>


        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <!-- Tiles API -->
        <!-- http://mvnrepository.com/artifact/org.apache.tiles/tiles-api -->
        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-api</artifactId>
            <version>3.0.8</version>
        </dependency>


        <!-- Tiles Core -->
        <!-- http://mvnrepository.com/artifact/org.apache.tiles/tiles-core -->
        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-core</artifactId>
            <version>3.0.8</version>
        </dependency>

        <!-- Tiles Servlet -->
        <!-- http://mvnrepository.com/artifact/org.apache.tiles/tiles-servlet -->
        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-servlet</artifactId>
            <version>3.0.8</version>
        </dependency>

        <!-- Tiles JSP -->
        <!-- http://mvnrepository.com/artifact/org.apache.tiles/tiles-jsp -->
        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-jsp</artifactId>
            <version>3.0.8</version>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/org.apache.tiles/tiles-request-api -->
        <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-request-api</artifactId>
            <version>1.0.6</version>
        </dependency>
        
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

5- Cấu hình Tiles View Resolver

TilesConfig.java

package org.o7planning.sbtiles.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import org.springframework.web.servlet.view.tiles3.TilesConfigurer;
import org.springframework.web.servlet.view.tiles3.TilesView;

@Configuration
public class TilesConfig {
    
    
    @Bean(name = "viewResolver")
    public ViewResolver getViewResolver() {
        UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();

        // TilesView 3
        viewResolver.setViewClass(TilesView.class);

        return viewResolver;
    }

    @Bean(name = "tilesConfigurer")
    public TilesConfigurer getTilesConfigurer() {
        TilesConfigurer tilesConfigurer = new TilesConfigurer();

        // TilesView 3
        tilesConfigurer.setDefinitions("/WEB-INF/tiles.xml");

        return tilesConfigurer;
    }
    
    

}

6- Tiles Definitions & Layout

Tập tin tiles.xml là nơi bạn định nghĩa các trang (page) trong ứng dụng của bạn. Và khai báo các thành phần hợp thành cho mỗi trang.
tiles.xml

<?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>  

    <!-- Base Define -->
    <definition name="base.definition"  
        template="/WEB-INF/layouts/classic.jsp">  
        <put-attribute name="title" value="" />  
        <put-attribute name="header" value="/WEB-INF/basefragments/_header.jsp" />  
        <put-attribute name="menu" value="/WEB-INF/basefragments/_menu.jsp" />  
        <put-attribute name="body" value="" />  
        <put-attribute name="footer" value="/WEB-INF/basefragments/_footer.jsp" />  
    </definition>  

    <!-- Home Page  -->
    <definition name="homePage" extends="base.definition">  
        <put-attribute name="title" value="Home Page" />  
        <put-attribute name="body" value="/WEB-INF/bodyfragments/_home.jsp" />  
    </definition>  
      
    <!-- ContactUs Page -->
    <definition name="contactusPage" extends="base.definition">  
        <put-attribute name="title" value="Contact Us" />  
        <put-attribute name="body" value="/WEB-INF/bodyfragments/_contactus.jsp" />  
    </definition>    

 
</tiles-definitions> 
Tập tin classic.jsp được sử dụng để sắp đặt vị trí các thành phần sẽ được hiển thị trên giao diện. Chẳng hạn như hình minh họa dưới đây:
classic.jsp

<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<html>
<head>
<title><tiles:getAsString name="title" /></title>
</head>

<body>
    <table width="100%">
        <tr>
            <td colspan="2">
                <tiles:insertAttribute name="header" />
            </td>
        </tr>
        <tr>
            <td width="20%" nowrap="nowrap">
                 <tiles:insertAttribute name="menu" />
             </td>
            <td width="80%">
                 <tiles:insertAttribute name="body" />
             </td>
        </tr>
        <tr>
            <td colspan="2">
                 <tiles:insertAttribute name="footer" />
            </td>
        </tr>
    </table>
</body>
</html>

7- JSP Fragments

/WEB-INF/basefragments/_menu.jsp

<div style="padding: 5px;">

    <ul>

        <li><a href="${pageContext.request.contextPath}/">Home</a></li>
        <li><a href="${pageContext.request.contextPath}/contactus">Contact Us</a></li>

    </ul>

</div>
/WEB-INF/basefragments/_header.jsp

<div style="background: #E0E0E0; height: 55px; padding: 5px;">
   <div style="float: left">
      <h1>My Site</h1>
   </div>

   <div style="float: right; padding: 10px; text-align: right;">

      Search <input name="search">

   </div>

</div>
/WEB-INF/basefragments/_footer.jsp

<div
   style="background: #E0E0E0; text-align: center; padding: 5px; margin-top: 10px;">
    
   @Copyright o7planning.org
    
</div>
/WEB-INF/bodyfragments/_home.jsp

<h2>Hi All</h2>

This is Home Page
/WEB-INF/bodyfragments/_contactus.jsp

Contact Us: o7planning.org
<br>
Address: ${address}
<br>
Phone: ${phone}
<br>
Email: ${email}

8- Controller

MainController.java

package org.o7planning.sbtiles.controller;

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

@Controller
public class MainController {

    @RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
    public String homePage(Model model) {
        return "homePage";
    }

    
    @RequestMapping(value = { "/contactus" }, method = RequestMethod.GET)
    public String contactusPage(Model model) {
        model.addAttribute("address", "Vietnam");
        model.addAttribute("phone", "...");
        model.addAttribute("email", "...");
        return "contactusPage";
    }
    
}

Xem thêm các chuyên mục: