兴趣爱好Javajava学习笔记(十) - web基础(thymeleaf)
执笔简介
物理视图
- 在Servlet中,将请求转发到一个HTML页面文件时,使用的完整的转发路径就是物理视图
- 如果我们把所有的HTML页面都放在某个统一的目录下,那么转发地址就会呈现出明显的规律:
1
| /pages/user/login.html /pages/user/login_success.html /pages/user/regist.html /pages/user/regist_success.html
|
逻辑视图
物理视图=视图前缀+逻辑视图+视图后缀
上面的例子中:
视图前缀 |
逻辑视图 |
视图后缀 |
物理视图 |
/pages/user/ |
login |
.html |
/pages/user/login.html |
/pages/user/ |
login_success |
.html |
/pages/user/login_success.html |
使用
导入jar包
配置上下文参数
1 2 3 4 5 6 7 8 9
| <context-param> <param-name>view-prefix</param-name> <param-value>/</param-value> </context-param> <context-param> <param-name>view-suffix</param-name> <param-value>.html</param-value> </context-param>
|
说明:param-value中设置的前缀、后缀的值不是必须叫这个名字,可以根据实际情况和需求进行修改
创建Servlet基类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.WebContext; import org.thymeleaf.templatemode.TemplateMode; import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;
public class ViewBaseServlet extends HttpServlet {
private TemplateEngine templateEngine;
@Override public void init() throws ServletException {
ServletContext servletContext = this.getServletContext();
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(servletContext);
templateResolver.setTemplateMode(TemplateMode.HTML);
String viewPrefix = servletContext.getInitParameter("view-prefix");
templateResolver.setPrefix(viewPrefix);
String viewSuffix = servletContext.getInitParameter("view-suffix");
templateResolver.setSuffix(viewSuffix);
templateResolver.setCacheTTLMs(60000L);
templateResolver.setCacheable(true);
templateResolver.setCharacterEncoding("utf-8");
templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
}
protected void processTemplate(String templateName, HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html;charset=UTF-8");
WebContext webContext = new WebContext(req, resp, getServletContext());
templateEngine.process(templateName, webContext, resp.getWriter()); } }
|
跳转thymeleaf页面
1 2 3 4 5 6 7 8 9
| protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String viewName = "target"; super.processTemplate(viewName, request, response); }
|
在html中使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body>
<p th:text="@{'/aaa/bbb/ccc'}">Thymeleaf将在这里显示一个解析出来的URL地址</p>
</body> </html>
|