什么是模板引擎?常见的模板引擎有哪些?thymeleaf的常用指令介绍。

提示:我们在开发过程中,尝尝需要将获取到的数据信息,以页面的形式展示给用户

目录

一、模板引擎

        1) 什么是模板引擎

        2) 模板引擎工作模式

        3)模板引擎分类

                ①JSP

                ②freemarker

                ③velocit

二、thymeleaf

        1)基本概念

        2)特点

        3)常用命令

          ①th:text和th:utext

          ②th:src和th:switch

          ③调用对象和对象语法糖th:object以及内置对象和内置对象语法糖

          ④th:action和th:href

          ⑤th:each

          ⑥th:if和th:unless


前言: 本篇文章将从模板引擎的基础概念,模板引擎的分类讲起,着重介绍最为常见的模板引擎Thymeleaf的执行流程和使用方法。

一、模板引擎

        1) 什么是模板引擎

                模板引擎是为了解决用户界面(显示)与业务数据(内容)分离而产生的。他可以产生特定格式的文档,例如:HTML、XML以及其他格式的文本格式。

        2) 模板引擎工作模式

                什么是模板引擎?常见的模板引擎有哪些?thymeleaf的常用指令介绍。_第1张图片

        3)模板引擎分类

                ①JSP

                  优点:

                  1.功能强大,可以写java代码。

                  2.支持JSP标签,(jsp.tag)

                  3.支持表达式语言(el表达式,jstl语法)

                  4.官方标准,用户多

                  5.性能良好,jsp编译成class文件执行,有很好的性能表现。

                缺点:

                  没有明显缺点,使用不当会出现破坏结果 

                ②freemarker

                  优点:

                  1.不能编写java代码,可以实现严格的mvc分离

                  2.性能非常不错

                  3.对JSP标签支持良好

                  4.内置大量常用功能,使用非常方便。

                  5.宏定义(类似jsp)

                  6.使用表达式语言

                缺点:

                  1.不是官方标准

                  2.用户群体少

                ③velocit

                  1.不能编写java代码,可以实现严格的mvc分离

                  2.性能良好

                  3.使用表达式语言

                缺点:

                  1.对jsp标签支持不够好

                  2.用户群体少,第三方标签库比jsp少

                  3.对jsp标签支持不够

                  4.很久没有维护

                  

二、thymeleaf

        1)基本概念

Thymeleaf 是新一代 Java 模板引擎,与 Velocity、FreeMarker 等传统 Java 模板引擎不同,Thymeleaf 支持 HTML 原型,其文件后缀为“.html”,因此它可以直接被浏览器打开,此时浏览器会忽略未定义的 Thymeleaf 标签属性,展示 thymeleaf 模板的静态页面效果;当通过 Web 应用程序访问时,Thymeleaf 会动态地替换掉静态内容,使页面动态显示。

        2)特点

Thymeleaf 模板引擎具有以下特点:

  • 动静结合:Thymeleaf 既可以直接使用浏览器打开,查看页面的静态效果,也可以通过 Web 应用程序进行访问,查看动态页面效果。
  • 开箱即用:Thymeleaf 提供了 Spring 标准方言以及一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
  • 多方言支持:它提供了 Thymeleaf 标准和 Spring 标准两种方言,可以直接套用模板实现 JSTL、 OGNL 表达式;必要时,开发人员也可以扩展和创建自定义的方言。
  • 与 SpringBoot 完美整合:SpringBoot 为 Thymeleaf 提供了的默认配置,并且还为 Thymeleaf 设置了视图解析器,因此 Thymeleaf 可以与 Spring Boot 完美整合。

            

        3)常用命令

          ①th:text和th:utext

  • 可以对表达式或变量进行计算求值;
  • 可以使用“+”进行文本拼接;
  • 可以获取后端传过来的request作用域中的数据(包括Model、ModelAndView作用域)。
package com.ape.view;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

/**
 * Servlet implementation class UserName
 */
@WebServlet("/UserName")
public class UserName extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	TemplateEngine templateEngine;  // 模板引擎
    ServletContextTemplateResolver templateResolver; //模板解析器
   
    @Override
    public void init() throws ServletException {
        super.init();
        templateEngine = new TemplateEngine();
        templateResolver = new ServletContextTemplateResolver(getServletContext());
        //设置要应用于此解析器解析的模板的模板模式。
        templateResolver.setTemplateMode("HTML5"); 
        //非严格的HTML5
//	      templateResolver.setTemplateMode("LEGACYHTML5");
        // 设置新的字符编码以读取模板资源。
        templateResolver.setCharacterEncoding("utf-8");
        // 设置要添加到所有模板名称的新(可选)前缀,以将模板名称转换为资源名称。
        templateResolver.setPrefix("/");
        //设置要添加到所有模板名称的新(可选)后缀,以将模板名称转换为资源名称。
        templateResolver.setSuffix(".html"); 
        //将模板缓存关闭,默认是true
        templateResolver.setCacheable(false);
        //给模板引擎设置模板解析器
        templateEngine.setTemplateResolver(templateResolver);
    }

	
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		//提供数据
		String name = "

周周

"; WebContext context = new WebContext(request, response, getServletContext()); context.setVariable("username", name); templateEngine.process("heihei", context,response.getWriter()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }




Insert title here



	
	

什么是模板引擎?常见的模板引擎有哪些?thymeleaf的常用指令介绍。_第2张图片

从上述结果我们可以看出,th:text标签是将一切内容都识别为纯文本;而th:utext标签可以识别html文本,并将其生效。
 

          ②th:src和th:switch

package com.ape.view;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

/**
 * Servlet implementation class UserName
 */
@WebServlet("/UserName")
public class UserName extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	TemplateEngine templateEngine;  // 模板引擎
    ServletContextTemplateResolver templateResolver; //模板解析器
   
    @Override
    public void init() throws ServletException {
        super.init();
        templateEngine = new TemplateEngine();
        templateResolver = new ServletContextTemplateResolver(getServletContext());
        //设置要应用于此解析器解析的模板的模板模式。
        templateResolver.setTemplateMode("HTML5"); 
        //非严格的HTML5
//	      templateResolver.setTemplateMode("LEGACYHTML5");
        // 设置新的字符编码以读取模板资源。
        templateResolver.setCharacterEncoding("utf-8");
        // 设置要添加到所有模板名称的新(可选)前缀,以将模板名称转换为资源名称。
        templateResolver.setPrefix("/");
        //设置要添加到所有模板名称的新(可选)后缀,以将模板名称转换为资源名称。
        templateResolver.setSuffix(".html"); 
        //将模板缓存关闭,默认是true
        templateResolver.setCacheable(false);
        //给模板引擎设置模板解析器
        templateEngine.setTemplateResolver(templateResolver);
    }

	
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		//提供数据
//		String name = "周周";
//		String sex = "女";
		int lvl=2;
		
		WebContext context = new WebContext(request, response, getServletContext());
		
//		context.setVariable("username", name);
//		context.setVariable("sex", sex);
		context.setVariable("lvl", lvl);
		
//		templateEngine.process("yunsuanfu", context,response.getWriter());
//		templateEngine.process("panduan", context,response.getWriter());
		templateEngine.process("fenzhi", context,response.getWriter());
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}




Insert title here


	

什么是模板引擎?常见的模板引擎有哪些?thymeleaf的常用指令介绍。_第3张图片

          ③调用对象和对象语法糖th:object以及内置对象和内置对象语法糖

package com.ape.view;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

import com.ape.bean.Student;

/**
 * Servlet implementation class StudentServlet
 */
@WebServlet("/StudentServlet")
public class StudentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	TemplateEngine templateEngine;  // 模板引擎
    ServletContextTemplateResolver templateResolver; //模板解析器
   
    @Override
    public void init() throws ServletException {
        super.init();
        templateEngine = new TemplateEngine();
        templateResolver = new ServletContextTemplateResolver(getServletContext());
        //设置要应用于此解析器解析的模板的模板模式。
        templateResolver.setTemplateMode("HTML5"); 
        //非严格的HTML5
//	      templateResolver.setTemplateMode("LEGACYHTML5");
        // 设置新的字符编码以读取模板资源。
        templateResolver.setCharacterEncoding("utf-8");
        // 设置要添加到所有模板名称的新(可选)前缀,以将模板名称转换为资源名称。
        templateResolver.setPrefix("/");
        //设置要添加到所有模板名称的新(可选)后缀,以将模板名称转换为资源名称。
        templateResolver.setSuffix(".html"); 
        //将模板缓存关闭,默认是true
        templateResolver.setCacheable(false);
        //给模板引擎设置模板解析器
        templateEngine.setTemplateResolver(templateResolver);
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		HttpSession session = request.getSession();
		
		//提供数据
		Student s = new Student();
		s.setSid(1);
		s.setSname("辰 辰");
		s.setBirthday(new Date());
		s.setSsex("男");
		
		session.setAttribute("stu", s);
		
		WebContext context = new WebContext(request, response, getServletContext());
		
		context.setVariable("student", s);
		
		templateEngine.process("student", context,response.getWriter());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}




Insert title here


	
	

 什么是模板引擎?常见的模板引擎有哪些?thymeleaf的常用指令介绍。_第4张图片

          ④th:action和th:href

  • action是在提交表单时候可以带值到下一个页面
  • href是在跳转连接时候可以带值到下一个页面
  • 在下一个页面获取两者携带的值是都是通过request.getParameter(name);方法。

语法:

全查主页面 

package com.ape.view;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;
import org.thymeleaf.context.WebContext;

import com.ape.bean.Student;
import com.ape.dao.DaoUtil;
import com.ape.mapper.StudentMapper;

/**
 * Servlet implementation class findALlStudent
 */
@WebServlet("/findAllStudent")
public class findAllStudent extends BaseServlet {
	private static final long serialVersionUID = 1L;
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 1. 处理乱码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		//获取资源
		SqlSession sqlSession = DaoUtil.getSqlSession();
		WebContext context = new WebContext(request, response, getServletContext());
		
		//获取数据
		StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
		List list = mapper.findAllStudent();
		context.setVariable("stulist", list);
		
		// 响应
		templateEngine.process("showstu", context, response.getWriter());
				
		//关闭资源
		sqlSession.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

 添加

package com.ape.view;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;
import org.thymeleaf.context.WebContext;

import com.ape.bean.Banji;
import com.ape.dao.DaoUtil;
import com.ape.mapper.BanjiMapper;

/**
 * Servlet implementation class addStudentServlet
 */
@WebServlet("/addStudentServlet")
public class addStudentServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//处理乱码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		//获取资源
		SqlSession sqlSession = DaoUtil.getSqlSession();
		WebContext context = new WebContext(request, response, getServletContext());
		
		//获取数据
		BanjiMapper mapper = sqlSession.getMapper(BanjiMapper.class);
		List list = mapper.findAllBanji();
		context.setVariable("bjlist", list);
		
		//响应
		templateEngine.process("addstu", context, response.getWriter());
		
		//关闭资源
		sqlSession.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
package com.ape.view;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;
import org.thymeleaf.context.WebContext;

import com.ape.bean.Banji;
import com.ape.dao.DaoUtil;
import com.ape.mapper.BanjiMapper;

/**
 * Servlet implementation class addStudentServlet
 */
@WebServlet("/addStudentServlet")
public class addStudentServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//处理乱码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		//获取资源
		SqlSession sqlSession = DaoUtil.getSqlSession();
		WebContext context = new WebContext(request, response, getServletContext());
		
		//获取数据
		BanjiMapper mapper = sqlSession.getMapper(BanjiMapper.class);
		List list = mapper.findAllBanji();
		context.setVariable("bjlist", list);
		
		//响应
		templateEngine.process("addstu", context, response.getWriter());
		
		//关闭资源
		sqlSession.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

删除 

package com.ape.view;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;

import com.ape.dao.DaoUtil;
import com.ape.mapper.StudentMapper;

/**
 * Servlet implementation class delStudentServlet
 */
@WebServlet("/delStudentServlet")
public class delStudentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取数据
		String sid = request.getParameter("sid");
		
		//获取资源
		SqlSession sqlSession = DaoUtil.getSqlSession();
		StudentMapper stumapper = sqlSession.getMapper(StudentMapper.class);
		int ret = stumapper.delStudent(Integer.parseInt(sid));
		
		//判断是否删除成功
		if(ret > 0) {
			sqlSession.commit();
		}else {
			sqlSession.rollback();
		}
		
		//重定向
		response.sendRedirect("findAllStudent");
		
		//关闭资源
		DaoUtil.closeSource(sqlSession);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

 修改

package com.ape.view;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;
import org.thymeleaf.context.WebContext;

import com.ape.bean.Banji;
import com.ape.bean.Student;
import com.ape.dao.DaoUtil;
import com.ape.mapper.BanjiMapper;
import com.ape.mapper.StudentMapper;

/**
 * Servlet implementation class updateStudentServlet
 */
@WebServlet("/updateStudentServlet")
public class updateStudentServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//处理乱码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		//获取资源
		SqlSession sqlSession = DaoUtil.getSqlSession();
		WebContext context = new WebContext(request, response, getServletContext());
		int sid =Integer.parseInt(request.getParameter("sid")); 
		
		//获取数据
		BanjiMapper mapper = sqlSession.getMapper(BanjiMapper.class);
		List list = mapper.findAllBanji();
		
		StudentMapper mapper2 = sqlSession.getMapper(StudentMapper.class);
		Student s = mapper2.findStudentBysid(sid);
		context.setVariable("bjlist", list);
		context.setVariable("stu", s);
		
		//响应
		templateEngine.process("updateStushow", context, response.getWriter());
		
		//关闭资源
		sqlSession.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
package com.ape.view;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;

import com.ape.bean.Student;
import com.ape.dao.DaoUtil;
import com.ape.mapper.StudentMapper;

/**
 * Servlet implementation class updateStudentControllerServlet
 */
@WebServlet("/updateStudentControllerServlet")
public class updateStudentControllerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 处理乱码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		//获取资源
		SqlSession sqlSession = DaoUtil.getSqlSession();
		
		//获取数据
		int sid = Integer.parseInt(request.getParameter("sid"));
		String sname = request.getParameter("sname");
		String birthday = request.getParameter("birthday");
		String ssex = request.getParameter("ssex");
		String classid = request.getParameter("classid");
		
		//创建对象,将数据存入对象中
		Student s = new Student();
		try {
			s.setBirthday(sdf.parse(birthday));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		s.setSid(sid);
		s.setClassid(Integer.parseInt(classid));
		s.setSname(sname);
		s.setSsex(ssex);
		
		System.out.println(s);
		//调用方法,将数据存入数据库
		StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
		int ret = mapper.updateStudent(s);
		System.out.println(ret);
		//判断是否修改成功,提交事务
		if (ret>0) {
			sqlSession.commit();
			out.print("");
			//重定向
			//response.sendRedirect("findAllStudent");
		} else {
			sqlSession.rollback();
			out.print("");
			//重定向
			//response.sendRedirect("findAllStudent");

		}
		
		//关闭资源
		sqlSession.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

 封装的BaseServlet

package com.ape.view;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;


@WebServlet("/BaseServlet")
public class BaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected TemplateEngine templateEngine;  // 模板引擎
	protected ServletContextTemplateResolver templateResolver; //模板解析器
	   
    @Override
    public void init() throws ServletException {
        super.init();
        templateEngine = new TemplateEngine();
        templateResolver = new ServletContextTemplateResolver(getServletContext());
        //设置要应用于此解析器解析的模板的模板模式。
        templateResolver.setTemplateMode("HTML5"); 
        //非严格的HTML5
//	      templateResolver.setTemplateMode("LEGACYHTML5");
        // 设置新的字符编码以读取模板资源。
        templateResolver.setCharacterEncoding("utf-8");
        // 设置要添加到所有模板名称的新(可选)前缀,以将模板名称转换为资源名称。
        templateResolver.setPrefix("/");
        //设置要添加到所有模板名称的新(可选)后缀,以将模板名称转换为资源名称。
        templateResolver.setSuffix(".html"); 
//将模板缓存关闭,默认是true
        templateResolver.setCacheable(false);
        //给模板引擎设置模板解析器
	        templateEngine.setTemplateResolver(templateResolver);
	    }
   

}

HTML部分

主页面





Insert title here


学生列表

学生编号 学生姓名 学生生日 学生性别 班级编号 操作
删除 修改
添加学生

添加 





Insert title here


添加学生

学生的姓名:
学生的生日:
学生的性别:
学生的班级:

 修改





Insert title here


修改学生

学生的姓名:
学生的生日:
学生的性别:
学生的班级:

运行结果

什么是模板引擎?常见的模板引擎有哪些?thymeleaf的常用指令介绍。_第5张图片

什么是模板引擎?常见的模板引擎有哪些?thymeleaf的常用指令介绍。_第6张图片

什么是模板引擎?常见的模板引擎有哪些?thymeleaf的常用指令介绍。_第7张图片

点击修改学生Servlet我们可以看到跳转后修改sid=1到修改页面 

          ⑤th:each

package com.ape.view;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.session.SqlSession;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

import com.ape.bean.Student;
import com.ape.dao.DaoUtil;
import com.ape.mapper.StudentMapper;

/**
 * Servlet implementation class StudentServlet
 */
@WebServlet("/StudentServlet")
public class StudentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	TemplateEngine templateEngine;  // 模板引擎
    ServletContextTemplateResolver templateResolver; //模板解析器
   
    @Override
    public void init() throws ServletException {
        super.init();
        templateEngine = new TemplateEngine();
        templateResolver = new ServletContextTemplateResolver(getServletContext());
        //设置要应用于此解析器解析的模板的模板模式。
        templateResolver.setTemplateMode("HTML5"); 
        //非严格的HTML5
//	      templateResolver.setTemplateMode("LEGACYHTML5");
        // 设置新的字符编码以读取模板资源。
        templateResolver.setCharacterEncoding("utf-8");
        // 设置要添加到所有模板名称的新(可选)前缀,以将模板名称转换为资源名称。
        templateResolver.setPrefix("/");
        //设置要添加到所有模板名称的新(可选)后缀,以将模板名称转换为资源名称。
        templateResolver.setSuffix(".html"); 
        //将模板缓存关闭,默认是true
        templateResolver.setCacheable(false);
        //给模板引擎设置模板解析器
        templateEngine.setTemplateResolver(templateResolver);
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		
		
		SqlSession sqlSession = DaoUtil.getSqlSession();
		StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
		List list = mapper.findAllStudent();
		
		
		
		WebContext context = new WebContext(request, response, getServletContext());
		
		context.setVariable("stulist", list);
		
		templateEngine.process("xunhuan", context,response.getWriter());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}




Insert title here
	


	
序号 学生编号 学生姓名 学生生日 学生性别 学生班级 隔行变色
欢迎[[${stulist.get(0)}]]欢迎

 

什么是模板引擎?常见的模板引擎有哪些?thymeleaf的常用指令介绍。_第8张图片

          ⑥th:if和th:unless

package com.ape.view;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

/**
 * Servlet implementation class UserName
 */
@WebServlet("/UserName")
public class UserName extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	TemplateEngine templateEngine;  // 模板引擎
    ServletContextTemplateResolver templateResolver; //模板解析器
   
    @Override
    public void init() throws ServletException {
        super.init();
        templateEngine = new TemplateEngine();
        templateResolver = new ServletContextTemplateResolver(getServletContext());
        //设置要应用于此解析器解析的模板的模板模式。
        templateResolver.setTemplateMode("HTML5"); 
        //非严格的HTML5
//	      templateResolver.setTemplateMode("LEGACYHTML5");
        // 设置新的字符编码以读取模板资源。
        templateResolver.setCharacterEncoding("utf-8");
        // 设置要添加到所有模板名称的新(可选)前缀,以将模板名称转换为资源名称。
        templateResolver.setPrefix("/");
        //设置要添加到所有模板名称的新(可选)后缀,以将模板名称转换为资源名称。
        templateResolver.setSuffix(".html"); 
        //将模板缓存关闭,默认是true
        templateResolver.setCacheable(false);
        //给模板引擎设置模板解析器
        templateEngine.setTemplateResolver(templateResolver);
    }

	
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		//提供数据
//		String name = "周周";
		String sex = "女";
//		int lvl=2;
		
		WebContext context = new WebContext(request, response, getServletContext());
		
		context.setVariable("username", name);
		context.setVariable("sex", sex);
//		context.setVariable("lvl", lvl);
		
//		templateEngine.process("yunsuanfu", context,response.getWriter());
		templateEngine.process("panduan", context,response.getWriter());
//		templateEngine.process("fenzhi", context,response.getWriter());
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}




Insert title here


	
	

什么是模板引擎?常见的模板引擎有哪些?thymeleaf的常用指令介绍。_第9张图片

 大家可以看到if为满足条件则运行并且显示HTML,unless为不满足条件时候执行,两者显示完成后继续执行if和unless并且后面显示结果会覆盖前面条件,所以看到的运行结果为第二行选中男选项。

       

     

         又是新的一周!加油宝子们!下个阶段的学习继续努力啊!!!

你可能感兴趣的:(java,开发语言)