maven+Thymeleaf笔记-1
来源:互联网 发布:淘宝刷一个单多少钱 编辑:程序博客网 时间:2024/05/18 00:08
环境的搭建
maven搭建web环境:参照:http://blog.csdn.net/caoxuekun/article/details/77336444
页面的访问案例:
a.引入thymeleaf
pom.xml:
<dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf</artifactId> <version>3.0.7.RELEASE</version> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring4</artifactId> <version>3.0.0.RELEASE</version> </dependency>
页面的访问:
web.xml中配置拦截器,拦截所有
<filter> <filter-name>gtvgfilter</filter-name> <filter-class>com.core.filter.GTVGFilter</filter-class> </filter> <filter-mapping> <filter-name>gtvgfilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
拦截器对应的类代码:
/* * ============================================================================= * * Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ============================================================================= */package com.core.filter;import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.thymeleaf.ITemplateEngine;import com.core.IGTVGController;import com.core.application.GTVGApplication;public class GTVGFilter implements Filter { private ServletContext servletContext; private GTVGApplication application; public GTVGFilter() { super(); } private static void addUserToSession(final HttpServletRequest request) { // Simulate a real user session by adding a user object// request.getSession(true).setAttribute("user", new User("John", "Apricot", "Antarctica", null)); } public void init(final FilterConfig filterConfig) throws ServletException { this.servletContext = filterConfig.getServletContext(); this.application = new GTVGApplication(this.servletContext); } public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { addUserToSession((HttpServletRequest)request); if (!process((HttpServletRequest)request, (HttpServletResponse)response)) { chain.doFilter(request, response); } } public void destroy() { // nothing to do } private boolean process(HttpServletRequest request, HttpServletResponse response) throws ServletException { try { // 这可以防止触发资源URL的引擎执行。 if ( request.getRequestURI().startsWith("/css") || request.getRequestURI().startsWith("/images") || request.getRequestURI().startsWith("/favicon")) { return false; } /* * 查询控制器/ URL映射并获得控制器处理请求。如果没有控制器可用,返回false,让其他的拦截器处理请求。 */ IGTVGController controller = this.application.resolveControllerForRequest(request); if (controller == null) { return false; } /* * 获取 TemplateEngine实例 */ ITemplateEngine templateEngine = this.application.getTemplateEngine(); /* * 响应头设置 */ response.setContentType("text/html;charset=UTF-8"); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); /* * 执行控制器和进程视图模板,将结果写入到response中 */ controller.process( request, response, this.servletContext, templateEngine); return true; } catch (Exception e) { try { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (final IOException ignored) { // Just ignore this } throw new ServletException(e); } }}
接口:
/* * ============================================================================= * * Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ============================================================================= */package com.core;import javax.servlet.ServletContext;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.thymeleaf.ITemplateEngine;public interface IGTVGController { public void process( HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, ITemplateEngine templateEngine) throws Exception;}
子类实体:
/* * ============================================================================= * * Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ============================================================================= */package com.core;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import javax.servlet.ServletContext;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.thymeleaf.ITemplateEngine;import org.thymeleaf.context.WebContext;public class HomeController implements IGTVGController { public HomeController() { super(); } public void process( final HttpServletRequest request, final HttpServletResponse response, final ServletContext servletContext, final ITemplateEngine templateEngine) throws Exception { WebContext ctx = new WebContext(request, response, servletContext, request.getLocale()); Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒"); //在home.html页面通过${today}获取访问的时间 ctx.setVariable("today", sdf.format(date)); templateEngine.process("home", ctx, response.getWriter()); }}
创建GTVGApplication负责创建模板引擎TemplateEngine和模板解析器ServletContextTemplateResolver实例
package com.core.application;import java.util.HashMap;import java.util.Map;import javax.servlet.ServletContext;import javax.servlet.http.HttpServletRequest;import org.thymeleaf.ITemplateEngine;import org.thymeleaf.TemplateEngine;import org.thymeleaf.templatemode.TemplateMode;import org.thymeleaf.templateresolver.ServletContextTemplateResolver;import com.core.HomeController;import com.core.IGTVGController;import com.core.ProductController;import com.core.ProductListController;public class GTVGApplication { private TemplateEngine templateEngine; private Map<String, IGTVGController> controllersByURL; public GTVGApplication(final ServletContext servletContext) { super(); //创建模板解析器 ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(servletContext); //默认是html模板 templateResolver.setTemplateMode(TemplateMode.HTML); //设置前缀和后缀 templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); //设置模板缓存的ttl时间 // Set template cache TTL to 1 hour. If not set, entries would live in cache until expelled by LRU templateResolver.setCacheTTLMs(Long.valueOf(3600000L)); // Cache is set to true by default. Set to false if you want templates to // be automatically updated when modified. //templateResolver.setCacheable(true); templateResolver.setCacheable(false);// 修改html后不用重启动项目 templateResolver.setCharacterEncoding("UTF-8");// 解决Thymeleaf中文乱码问题 //实例化模板引擎 this.templateEngine = new TemplateEngine(); this.templateEngine.setTemplateResolver(templateResolver); this.controllersByURL = new HashMap<String, IGTVGController>(); //设置url的拦截和对应的控制类 this.controllersByURL.put("/", new HomeController()); this.controllersByURL.put("/product", new ProductController()); this.controllersByURL.put("/products", new ProductListController());// this.controllersByURL.put("/order/list", new OrderListController());// this.controllersByURL.put("/order/details", new OrderDetailsController());// this.controllersByURL.put("/subscribe", new SubscribeController());// this.controllersByURL.put("/userprofile", new UserProfileController()); } public IGTVGController resolveControllerForRequest(final HttpServletRequest request) { final String path = getRequestPath(request); return this.controllersByURL.get(path); } public ITemplateEngine getTemplateEngine() { return this.templateEngine; } private static String getRequestPath(final HttpServletRequest request) { String requestURI = request.getRequestURI(); final String contextPath = request.getContextPath(); final int fragmentIndex = requestURI.indexOf(';'); if (fragmentIndex != -1) { requestURI = requestURI.substring(0, fragmentIndex); } if (requestURI.startsWith(contextPath)) { return requestURI.substring(contextPath.length()); } return requestURI; }}
方式时的url拦截
this.controllersByURL.put("/", new HomeController());
拦截’ / ‘到HomeController类中
templateEngine.process("home", ctx, response.getWriter());
有设置的‘home’和GTVGApplication类的模板解释器设置的前后缀
//设置前缀和后缀 templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html");
拼接访问到/WEB-INF/templates/home.html页面。
在home.html页面相同目录位置配置home.properties资源文件
home.properties:
home.welcome=Welcome to our grocery store, {0} (from default messages)!logo=Good Thymes Virtual Grocery logodate.format=MMMM dd'','' yyyy
在home.html中可以用
<p th:text="#{home.welcome}">Welcome to our grocery store, Sebastian!</p>
拿到home.properties资源文件中的键值对
如果home.properties中的键值对含有‘<b>’,可以通过
<p th:utext="#{home.welcome}">Welcome to our grocery store, Sebastian!</p>
页面获取一个实体案例:
定一个product类:
package com.entity;import java.math.BigDecimal;import java.util.ArrayList;import java.util.List;public class Product { private Integer id = null;//产品id private String name = null;//产品名称 private String price = null;//产品的价格 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; }}
定义一个获取实体的类:
package com.service;import java.util.List;import com.entity.Product;public class ProductService { //返回一个产品instance public Product getOneProduct(){ Product product = new Product(); product.setId(1); product.setName("曹雪坤的做的产品"); product.setPrice("100"); return product; }}
定义一个product控制器类:
package com.core;import javax.servlet.ServletContext;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.thymeleaf.ITemplateEngine;import org.thymeleaf.context.WebContext;import com.entity.Product;import com.service.ProductService;public class ProductController implements IGTVGController { public void process( final HttpServletRequest request, final HttpServletResponse response, final ServletContext servletContext, final ITemplateEngine templateEngine) throws Exception { final ProductService productService = new ProductService(); //获取一个Product实例 final Product product = productService.getOneProduct(); final WebContext ctx = new WebContext(request, response, servletContext, request.getLocale()); ctx.setVariable("product", product); templateEngine.process("product", ctx, response.getWriter()); }}
在GTVGApplication添加对应的访问拦截:
this.controllersByURL.put("/product", new ProductController());
在WEB-INF/templates中定义product.html页面
<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"> <head> <title>Good Thymes Virtual Grocery</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" type="text/css" media="all" href="../../css/gtvg.css" /> </head> <body> <div> <img src="../../images/gtvglogo.png" alt="GTVG logo" title="GTVG logo" th:src="@{/images/gtvglogo.png}" th:alt-title="#{logo}" /> </div> <p> <span th:text="${product.name}"></span> <span th:text="${product.id}"></span> <span th:text="${product.price}"></span> </p> </body></html>
通过访问http://localhost:8080/thymeleafNote1/product
便可以实体的属性写道到页面标签中
获取集合类型的和按照id取对象
修改ProductService
package com.service;import java.util.ArrayList;import java.util.List;import com.entity.Product;public class ProductService { //返回一个产品instance public Product getOneProduct(){ Product product = new Product(); product.setId(1); product.setName("曹雪坤的做的产品"); product.setPrice("100"); return product; } public Product getProductById(Integer id){ Product product = new Product(); product.setId(id); product.setName("xxxx"+id); product.setPrice("xxxxxxxxxxxxxx"+id); return product; } public List<Product> getAllProduct(){ List<Product> lists = new ArrayList<Product>(); Product product1 = new Product(); Product product2 = new Product(); Product product3 = new Product(); Product product4 = new Product(); Product product5 = new Product(); product1.setId(1); product1.setName("曹雪坤的做的产品"); product1.setPrice("100"); product2.setId(2); product2.setName("caoxuekun"); product2.setPrice("100000"); product3.setId(3); product3.setName("曹3的产品"); product3.setPrice("300"); product4.setId(4); product4.setName("曹4做的产品"); product4.setPrice("400"); product5.setId(5); product5.setName("曹5雪坤的做的产品"); product5.setPrice("500"); lists.add(product5); lists.add(product4); lists.add(product3); lists.add(product2); lists.add(product1); return lists; }}
修改ProductController:
package com.core;import javax.servlet.ServletContext;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.thymeleaf.ITemplateEngine;import org.thymeleaf.context.WebContext;import com.entity.Product;import com.service.ProductService;public class ProductController implements IGTVGController { public void process( final HttpServletRequest request, final HttpServletResponse response, final ServletContext servletContext, final ITemplateEngine templateEngine) throws Exception { Integer pid = null;//对象的id if(!(request.getParameter("pid") == null)){ pid = new Integer(request.getParameter("pid")); } final ProductService productService = new ProductService(); Product product = null; if(!(pid == null)){ product = productService.getProductById(pid); }else{ //获取一个Product实例 product = productService.getOneProduct(); } final WebContext ctx = new WebContext(request, response, servletContext, request.getLocale()); ctx.setVariable("product", product); templateEngine.process("product", ctx, response.getWriter()); }}
添加集合的处理控制器:
package com.core;import java.util.List;import javax.servlet.ServletContext;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.thymeleaf.ITemplateEngine;import org.thymeleaf.context.WebContext;import com.entity.Product;import com.service.ProductService;public class ProductListController implements IGTVGController{ @Override public void process(HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, ITemplateEngine templateEngine) throws Exception { final ProductService ps = new ProductService(); List<Product> lists = ps.getAllProduct(); final WebContext ctx = new WebContext(request, response, servletContext, request.getLocale()); ctx.setVariable("lists", lists); templateEngine.process("products", ctx, response.getWriter()); }}
在GTVGApplication添加url的拦截
this.controllersByURL.put("/products", new ProductListController());
添加products页面和资源文件
products.html:
<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head><title>Good Thymes Virtual Grocery</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><style type="text/css"> table{text-align:center;border-collapse:collapse;/*折叠边框*/} td{border:1px solid red;padding: 4px 33px;} th{border:1px solid red;padding: 4px 33px;}</style></head><body>products:<br> <table > <tr> <th>产品名称</th> <th>产品价格</th> <th>产品id是否为1</th> <th>产品的详细内容</th> </tr> <tr th:each="product : ${lists}"> <td th:text="${product.name}"></td> <td th:text="${product.price}"></td> <td th:text="${product.id == 1}?#{yes}:#{no}"></td> <td> <a th:href="@{/product(pid=${product.id})}">详细</a></td> </tr> </table> <a th:href="@{/}">返回到主页</a></body></html>
properties文件
yes=\u4EA7\u54C1id\u4E3A1no=\u4EA7\u54C1id\u4E0D\u4E3A1
- maven+Thymeleaf笔记-1
- maven+thymeleaf笔记-2
- maven+thymeleaf笔记-3
- Thymeleaf 笔记
- thymeleaf 笔记
- Thymeleaf+Spring+Maven MacOS
- java鬼混笔记:springboot之thymeleaf 1:简单的thymeleaf例子
- thymeleaf 学习笔记
- thymeleaf 学习笔记
- thymeleaf 学习笔记
- thymeleaf 学习笔记
- thymeleaf 学习笔记
- thymeleaf学习笔记
- thymeleaf 学习笔记
- thymeleaf 学习笔记
- Thymeleaf学习笔记
- thymeleaf 学习笔记
- thymeleaf的使用笔记
- 微信公众号开发(五)个性化菜单
- VBA遍历文件夹并正则表达式匹配文本所在位置
- 关于错误:Uncaught Error: Bootstrap's JavaScript requires jQuery bootstrap.js:8 at bootstrap.js:8
- UnityShader从入门到放弃(四)漫反射—逐顶点光照
- 大数据常见150坑
- maven+Thymeleaf笔记-1
- Android中的四大组件Service
- Git的简单使用
- POJ总结(2255)
- 百度云的高速下载技巧系列1---油猴插件和脚本(PC)
- nginx静态资源缓存策略配置
- SPPNET 和RCNN
- 读取一组电话号码簿(由姓名和手机号码组成),将重复出现的项删除(姓名和电话号码都相同的项为重复项,只保留第一次出现的项),并对姓名相同手机号码不同的项进行如下整理。
- 用BufferedReader和BufferedWriter实现对文章的敏感字符用****代替