Code ví dụ Spring MVC FreeMarker Hello World + Maven + Eclipse
(Xem lại: FreeMarker là gì? Giới thiệu Apache FreeMarker)
(Xem thêm: Code ví dụ Spring Boot FreeMarker)
FreeMarker là một template engine cho nền tảng Java. Nó đọc các file mẫu và kết hợp với các đối tượng Java để tạo đầu ra văn bản
Các công nghệ sử dụng:
Tạo maven project
Cấu trúc Project sau khi hoàn thành:
Thư viện sử dụng:
<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>stackjava.com</groupId> <artifactId>SpringMVCFreeMarker</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.source>1.8</maven.compiler.source> <spring.version>5.0.2.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency> </dependencies> </project>
File 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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name>SpringMVCFreeMarker</display-name> <servlet> <servlet-name>spring-mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring-mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
File Spring config:
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <context:component-scan base-package="stackjava.com" /> <!-- freemarker config --> <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath" value="/WEB-INF/views/" /> </bean> <!-- View resolvers can also be configured with ResourceBundles or XML files. If you need different view resolving based on Locale, you have to use the resource bundle resolver. --> <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> <property name="prefix" value="" /> <property name="suffix" value=".ftl" /> </bean> </beans>
Bean freemarkerConfig
cấu hình FreeMarker: templateLoaderPath
chỉ rõ các template nằm ở đâu
Bean viewResolver
cấu hình mvc với FreeMarker như prefix, suffix (đuôi mở rộng), có cache hay không…
File model:
package stackjava.com.springFreeMarker.model; public class Product { private int id; private String name; private int quantity; // constructor - getter/setter }
File Controller:
Trang index sẽ hiển thị tên lấy từ url, nếu không truyền param vào url thì name sẽ là “Anonymous”
package stackjava.com.springFreeMarker.controller; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import stackjava.com.springFreeMarker.model.Product; @Controller public class BaseController { @RequestMapping("/") public String index(@RequestParam(name = "name", required = false) String name, Model model) { if (name == null) { name = "Anonymous"; } String welcomeMessage = "Hi " + name + "! Welcome to SpringMVC FreeMarker"; model.addAttribute("message", welcomeMessage); return "index"; } @GetMapping("/getProducts") public String getProducts(Model model) { List<Product> products = new ArrayList<>(); products.add(new Product(1, "Iphone XS", 10)); products.add(new Product(2, "SamSung S9", 12)); products.add(new Product(3, "Nokia", 23)); model.addAttribute("products", products); return "productList"; } }
File view:
<!DOCTYPE html> <html> <head> <title>stackjava.com Demo Spring MVC FreeMarker</title> </head> <body> <h2 style="color: red;">${message}</h2> <a href="getProducts">Get Products</a> </body> </html>
<!DOCTYPE html> <html> <head> <title>Demo Spring MVC FreeMarker</title> </head> <body> <table border = "1"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Quantity</th> </tr> </thead> <tbody> <#list products as item> <tr> <td>${item.id}</td> <td>${item.name}</td> <td>${item.quantity}</td> </tr> </#list> </tbody> </table> </body> </html>
Demo:
Run project trên server (ở đây mình chạy trên tomcat):
Thêm param name vào url
Click vào link Get Products
Okay, Done!
Download code ví dụ trên tại đây.
References: https://freemarker.apache.org/