CÔNG NGHỆ THÔNG TIN >> BÀI VIẾT CHỌN LỌC

Tạo bố cục-Layout trong Spring Web MVC sử dụng Apache Tile 3

Đăng lúc: 07:08 PM - 01/11/2023 bởi Charles Chung - 1162

Apache Tiles là một mã nguồn mở phát triển bởi Apache, nó là một framework/engine thực hiện việc tạo template, trong bài viết này tôi sẽ hướng dẫn các bạn sử dụng Apache Tiles trong Spring Web MVC.

1. Kiến thức cần có

  • Lập trình Java Core
  • HTML - CSS - JavaScript
  • JSP và Servlet

2. Các bước tạo ứng dụng Spring Web MVC và sử dụng Apache Tiles

Bước 1: Tạo Dynamic Web Project (xem chi tiết ở đây)

  • Khởi động Eclispe IDE -> vào menu File -> New -> Dynamic Web Project -> Nhập tên "SpringWebMVCLayoutTile"
  • Tiếp tục kích vào Next -> Next -> Chọn Generate web.xml deyployment desciptor -> Kích Finish

Bước 2: Convert sang Maven Project

  • Kích chuột phải vào Project vừa tạo -> Configure -> Convert to Maven Project -> Finish

Bước 3: Khai báo các Maven Dependencies cần thiết

  • Mở file pom.xml và cấu hình các Maven Dependencies gồm: spring web, web mvc, servlet api, jsp api, jstl (giống bài này) chỉ bổ sung thêm đoạn Apache tiles vào.

<!-- https://mvnrepository.com/artifact/org.apache.tiles/tiles-jsp -->

<dependency>

<groupId>org.apache.tiles</groupId>

<artifactId>tiles-extras</artifactId>

<version>3.0.7</version>

</dependency>

Bước 4: Cấu hình ứng dụng Spring Web Mvc

  • Trong thư mục WEB-INF tạo thư mục views và tệp tin spring-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:p="http://www.springframework.org/schema/p"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:mvc="http://www.springframework.org/schema/mvc"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd

http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

 

<!-- chỉ ra các package chứa các lớp java được đăng như các bean -->

<context:component-scan

base-package="controllers" />

<!-- chỉ tìm kiếm các bean trong cùng context application được định nghĩa -->

<context:annotation-config />

<!-- mặc định các basic components được ủy quyền gửi request tới các controller -->

<mvc:annotation-driven />

<!-- cấu hình resoures tĩnh như css, js, images... -->

<mvc:resources mapping="/resources/**"

location="/resources/" />

<!-- tạo bean tiles cấu hình đường dẫn tệp tin xml chưa các định nghĩa về template view -->

<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">

<property name="definitions">

<list>

<value>/WEB-INF/home-tiles.xml</value>

<value>/WEB-INF/admin-tiles.xml</value>

</list>

</property>

<property name="checkRefresh" value="true" />

</bean>

<!-- tạo bean viewResolver sử dụng cấu hình trong TilesView -->

<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">

<property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView" />

</bean>

</beans>

 

  • Nếu bạn không sử dụng file spring-servlet.xml cấu hình thì cấu hình bằng code java với tệp tin configuration/SpringConfiguration.Java

package configuration;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.ViewResolver;

import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import org.springframework.web.servlet.view.tiles3.TilesConfigurer;

import org.springframework.web.servlet.view.tiles3.TilesViewResolver;

@Configuration

@EnableWebMvc

@ComponentScan(basePackages = {"controllers"})

public class SpringConfiguration extends WebMvcConfigurerAdapter {

@Bean

public TilesConfigurer tileConfigurer() {

TilesConfigurer config=new TilesConfigurer();

config.setDefinitions(new String[] {"/WEB-INF/home-tiles.xml","/WEB-INF/admin-tiles.xml"});

config.setCheckRefresh(true);

return config;

}

@Bean

public ViewResolver viewResolver() {

TilesViewResolver viewResolver=new TilesViewResolver();

return viewResolver;

}

@Override

public void addResourceHandlers(ResourceHandlerRegistry registry) {

registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");

}

}

  • Mở tệp web.xml và cấu hình vào bên trong thẻ <web-app> như sau:

<!-- Add filter process UTF-8 -->

<filter>

<filter-name>encodingFilter</filter-name>

<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

<init-param>

<param-name>encoding</param-name>

<param-value>UTF-8</param-value>

</init-param>

<init-param>

<param-name>forceEncoding</param-name>

<param-value>true</param-value>

</init-param>

</filter>

<filter-mapping>

<filter-name>encodingFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

<!-- Add Spring MVC DispatcherServlet as front controller -->

<servlet>

<servlet-name>spring</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<init-param>

<param-name>contextConfigLocation</param-name>

<param-value>/WEB-INF/spring-servlet.xml</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>spring</servlet-name>

<url-pattern>/</url-pattern>

</servlet-mapping>

  • Nếu bạn không sử dụng file web.xml cấu hình thì cấu hình bằng code java với tệp configuration/WebInitializer.java

package configuration;

import javax.servlet.ServletContext;

import javax.servlet.ServletException;

import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;

import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import org.springframework.web.servlet.DispatcherServlet;

public class WebInitializer implements WebApplicationInitializer {

@Override

public void onStartup(ServletContext servletContext) throws ServletException {

servletContext.setRequestCharacterEncoding("UTF-8");

servletContext.setResponseCharacterEncoding("UTF-8");

AnnotationConfigWebApplicationContext ctx=new AnnotationConfigWebApplicationContext();

ctx.register(SpringConfiguration.class);

ctx.setServletContext(servletContext);

ServletRegistration.Dynamic servlet=servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));

servlet.setLoadOnStartup(1);

servlet.addMapping("/");

}

}

Bước 5: Tạo cấu trúc thư mục chứa tài nguyên và chứa các view

  • Tạo cấu trúc thư mục tệp tin như hình dưới

  • Tệp home-tiles.xml: định nghĩa template trang chủ và danh sách view

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

<!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN" "http://tiles.apache.org/dtds/tiles-config_2_0.dtd">

<tiles-definitions>

<!-- Định nghĩa các view default -->

<definition name="homelayout" template="/WEB-INF/views/home/layouts/homelayout.jsp">

<put-attribute name="title" value="Ví dụ về Apache tile 3" type="string" />

<put-attribute name="footer" value="/WEB-INF/views/home/layouts/footer.jsp" />

<put-attribute name="menubar" value="/WEB-INF/views/home/layouts/menubar.jsp" />

<put-attribute name="body" value="" />

</definition>

<!-- Định nghĩa các view khác-->

<definition name="home" extends="homelayout">

<put-attribute name="body" value="/WEB-INF/views/home/home.jsp" />

</definition>

<definition name="listProduct" extends="homelayout">

<put-attribute name="body" value="/WEB-INF/views/home/product/listProduct.jsp" />

</definition>

<definition name="addProduct" extends="homelayout">

<put-attribute name="body" value="/WEB-INF/views/home/product/addProduct.jsp" />

</definition>

<definition name="about" extends="homelayout">

<put-attribute name="body" value="/WEB-INF/views/home/about.jsp" />

</definition>

<definition name="contact" extends="homelayout">

<put-attribute name="body" value="/WEB-INF/views/home/contact.jsp" />

</definition>

</tiles-definitions>

 

  • Tệp admin-tiles.xml: định nghĩa template trang quản trị

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

<!DOCTYPE tiles-definitions PUBLIC

"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"

"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">

<tiles-definitions>

<!-- Đinh nghĩa các view default vào đây -->

<definition name="adminlayout" template="/WEB-INF/views/admin/layouts/adminlayout.jsp">

</definition>

<!-- Đinh nghĩa các view khác vào đây -->

</tiles-definitions>

  • Tệp homelayout.jsp: thiết kế giao diện template trang chủ

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title><tiles:insertAttribute name="title" /></title>

<link rel="stylesheet" href="${pageContext.servletContext.contextPath}/resources/css/bootstrap.min.css"/>

<link rel="stylesheet" href="${pageContext.servletContext.contextPath}/resources/css/home.css"/>

</head>

<body>

<div id="container">

<tiles:insertAttribute name="menubar" />

<tiles:insertAttribute name="body" />

<tiles:insertAttribute name="footer" />

</div>

<script

src="${pageContext.servletContext.contextPath}/resources/js/jquery-3.3.1.slim.min.js"></script>

<script

src="${pageContext.servletContext.contextPath}/resources/js/popper.min.js" /></script>

<script

src="${pageContext.servletContext.contextPath}/resources/js/bootstrap.min.js" /></script>

</body>

</html>

 

  • Tệp menubar.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">

<a class="navbar-brand" href="#">BKAP</a>

<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">

<span class="navbar-toggler-icon"></span>

</button>

<div class="collapse navbar-collapse" id="navbarsExampleDefault">

<ul class="navbar-nav mr-auto">

<li class="nav-item active">

<a class="nav-link" href="trang-chu">Trang chủ <span class="sr-only">(current)</span></a>

</li>

<li class="nav-item">

<a class="nav-link" href="danh-sach-san-pham">Sản phẩm</a>

</li>

<li class="nav-item">

<a class="nav-link" href="gioi-thieu">Giới thiêu</a>

</li>

<li class="nav-item">

<a class="nav-link" href="lien-he">Liên hệ</a>

</li>

</ul>

<form class="form-inline my-2 my-lg-0">

<input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search">

<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Tìm kiếm</button>

</form>

</div>

</nav>

 

  • Tệp footer.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<footer class="footer">

<div class="container">

<span class="text-muted">Copyright by HANAM88-2023</span>

</div>

</footer>

 

  • Tệp home.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<h3>Trang chủ</h3>

 

  • Tệp about.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<h3>Giới thiệu</h3>

 

  • Tệp contact.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<h3>Liên hệ</h3>

 

  • Tệp addProduct.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<h1>Thêm sản phẩm</h1>

<a href="them-san-pham">Thêm mới</a>

 

  • Tệp listProduct.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<h1>Danh sách sản phẩm</h1>

 

  • Tệp controllers/HomeController.java

package controllers;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;

@Controller

public class HomeController {

@RequestMapping(value={"/","/trang-chu"})

public String index(Model model) {

return "home";

}

@RequestMapping("/danh-sach-san-pham")

public String listProduct(Model model) {

return "listProduct";

}

@RequestMapping("/them-san-pham")

public String addProduct(Model model) {

return "addProduct";

}

@RequestMapping("/gioi-thieu")

public String about(Model model) {

return "about";

}

@RequestMapping("/lien-he")

public String contact(Model model) {

return "contact";

}

}

  • Tệp home.css

body {

/* Margin bottom by footer height */

margin-top:80px;

}

.footer {

position: absolute;

bottom: 0;

width: 100%;

/* Set the fixed height of the footer here */

height: 60px;

line-height: 60px; /* Vertically center the text there */

background-color: #f5f5f5;

}

body > .container {

padding: 60px 15px 0;

}

.footer > .container {

padding-right: 15px;

padding-left: 15px;

}

code {

font-size: 80%;

}

 

  • Các tài nguyên khác như css, js: tải từ trên mạng về

Bước 6: Run application

Kích chuột phải vào project chọn Run As -> Run on Server -> Tomcat v9.0

Kích để tải source code bài Tạo bố cục-Layout trong Spring Web MVC sử dụng Apache Tile 3

Training online liên hệ: Charles Chung

Video

thay lời cảm ơn!

QUẢNG CÁO - TIẾP THỊ