模板引擎的实现原理_模板引擎和vue区别

模板引擎的实现原理_模板引擎和vue区别提示:我们在开发过程中,尝尝需要将获取到的数据信息,以页面的形式展示给用户目录一、模板引擎1)什么是模板引擎2)模板引擎工作模式3)模板引擎分类①JSP②freemarker③velocit二、

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

目录

一、模板引擎

        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) 模板引擎工作模式

                模板引擎的实现原理_模板引擎和vue区别

        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 = "<h1>周周</h1>";
		
		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);
	}

}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

	<!-- OGNL表达式 -->
	<h1 th:text="${username}"></h1>
	<h1 th:utext="${username}"></h1>

</body>
</html>

模板引擎的实现原理_模板引擎和vue区别

从上述结果我们可以看出,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);
	}

}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<div th:switch="${lvl}">
		<img src="img/2.png" th:case="1">
		<img src="img/3.png" th:case="2">
		<img src="img/4.png" th:case="3">
		<img src="img/5.png" th:case="4">
		<img src="img/1.png" th:case="*">
	</div>

</body>
</html>

模板引擎的实现原理_模板引擎和vue区别

          ③调用对象和对象语法糖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);
	}

}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<span th:text="${student.sid}"></span>
	<div th:text="${student.sname}"></div>
	<input th:value="${student.ssex}">
	<p th:text="${student.birthday}"></p>
	<span th:text="${student.classid}"></span>
	
	<!-- 获取对象数据 -->
	<div th:object="${student}">
		<span th:text="*{sid}"></span>
		<div th:text="*{sname}"></div>
		<input th:value="*{ssex}">
		<p th:text="*{birthday}"></p>
		<span th:text="*{classid}"></span>
	</div>
	
	<h1 th:text="${#session.getAttribute('stu')['sname']}"></h1>
	<h1 th:text="${session.stu.sname}"></h1>
	
	<!-- 调用方法 -->
	<div th:text="${student.show()}"></div>
	
	<!-- java的方法 -->
	<div th:text="${student.sname.split(' ')[0]}"></div>
	<div th:text="${student.sname.split(' ')[1]}"></div>

</body>
</html>

 模板引擎的实现原理_模板引擎和vue区别

          ④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<Student> 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<Banji> 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<Banji> 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<Banji> 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("<script type=\"text/javascript\">\r\n"
					+ "			alert(\"修改成功\");\r\n "
					+ "location.href=\"findAllStudent\";"
					+ "		</script>");
			//重定向
			//response.sendRedirect("findAllStudent");
		} else {
			sqlSession.rollback();
			out.print("<script type=\"text/javascript\">\r\n"
					+ "			alert(\"修改失败\");\r\n "
					+ "location.href=\"findAllStudent\";"
					+ "		</script>");
			//重定向
			//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部分

主页面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>学生列表</h1>
<table border="1">
		<tr>
			<th>学生编号</th>
			<th>学生姓名</th>
			<th>学生生日</th>
			<th>学生性别</th>
			<th>班级编号</th>
			<th>操作</th>
		</tr>
		<tr th:each="item,stat : ${stulist}">
			<td th:text="${stat.count}"></td>
			<td th:text="${item.sname}"></td>
			<td th:text="${#dates.format(item.birthday,'yyyy-MM-dd')} ?: '没有生日'"></td>
			<td th:text="${item.ssex}"></td>
			<td th:text="${item.classid}"></td>
			<td>
				<!-- th:href="@{url(key=value,key2=value2)}" -->
				<a th:href="@{delStudentServlet(sid=${item.sid})}">删除</a>
				<a th:href="@{updateStudentServlet(sid=${item.sid})}">修改</a>
			</td>
		</tr>
		<tr>
			<td colspan="6"><a th:href="@{addStudentServlet}">添加学生</a></td>
		</tr>
	</table>
</body>
</html>

添加 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>添加学生</h1>
<form action="addStudentControllerServlet" method="post">
	学生的姓名:<input type="text" name="sname" /><br>
	学生的生日:<input type="date" name="birthday" /><br>
	学生的性别:<input type="radio" name="ssex" value="男" checked />🚹
			 <input type="radio" name="ssex" value="女"  />🚺<br>
	学生的班级:<select name="classid">
				<option  th:each=" bj : ${bjlist}" th:value="${bj.classid}" th:text="${bj.classname}" ></option>
			</select>
	<br>
	<input type="submit" value="添加" />
</form>
</body>
</html>

 修改

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>修改学生</h1>
<form action="updateStudentControllerServlet" method="post">
	<input type="hidden" name="sid" th:value="${stu.sid}">
	学生的姓名:<input type="text" name="sname" th:value="${stu.sname}" /><br>
	学生的生日:<input type="date" name="birthday" th:value="${#dates.format(stu.birthday,'yyyy-MM-dd')}" /><br>
	学生的性别:<input type="radio" name="ssex" value="男" th:checked="${stu.ssex}=='男'" />🚹
			 <input type="radio" name="ssex" value="女" th:checked="${stu.ssex}=='女'" />🚺<br>
	学生的班级:<select name="classid">
				<option  th:each=" bj : ${bjlist}" th:value="${bj.classid}" th:text="${bj.classname}" th:selected="${stu.classid}==${bj.classid}" ></option>
			  </select>
	<br>
	<input type="submit" value="修改" />
</form>
</body>
</html>

运行结果

模板引擎的实现原理_模板引擎和vue区别

模板引擎的实现原理_模板引擎和vue区别

模板引擎的实现原理_模板引擎和vue区别

点击修改学生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<Student> 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);
	}

}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
	<style>
		.red{
			background: red;
		
		}
		.blue{
			background: blue;
		
		}
	
	</style>
</head>
<body>
	<table border="2" style="border-collapse: collapse;">
		<tr>
			<th>序号</th>
			<th>学生编号</th>
			<th>学生姓名</th>
			<th>学生生日</th>
			<th>学生性别</th>
			<th>学生班级</th>
			<th>隔行变色</th>
		</tr>
		<tr th:each="item,stat:${stulist}" th:classappend="${stat.odd?'red':'blue'}">
		<td th:text="${item.sid}"></td>
			<td th:text="${stat.count}"></td>
			<td th:text="${item.sname}"></td>
			<td th:text="${#dates.format(item.birthday,'yyyy-MM-dd')}?:'没有生日!'"></td>
			<td th:text="${item.ssex}"></td>
			<td th:text="${item.classid}"></td>
			<!--隔行变色(奇数为true)  -->
			<td th:text="${stat.odd}"></td>
		</tr>
	</table>
	
<!-- 打印到控制台 -->
	<div><span style="color:red">欢迎</span>[[${stulist.get(0)}]]<span style="color:red">欢迎</span></div>
	<script type="text/javascript">
		alert('[[${stulist.get(2)}]]');
	</script>

</body>
</html>

 模板引擎的实现原理_模板引擎和vue区别

模板引擎的实现原理_模板引擎和vue区别

          ⑥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);
	}

}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<!-- 条件成立选择 -->
	<div th:if = "${sex}=='男'">
		<input type="radio" name="sex" value="男" checked="checked">男
		<input type="radio" name="sex" value="女">女
		</div>
		
	<div th:if = "${sex}=='女'">
		<input type="radio" name="sex" value="男">男
		<input type="radio" name="sex" value="女" checked="checked">女
		</div>
	
	<!-- 条件成立不选择 -->	
	<div th:unless = "${sex}=='男'">
		<input type="radio" name="sex" value="男" checked="checked">男
		<input type="radio" name="sex" value="女">女
		</div>
		
	<div th:unless = "${sex}=='女'">
		<input type="radio" name="sex" value="男">男
		<input type="radio" name="sex" value="女" checked="checked">女
		</div>

</body>
</html>

模板引擎的实现原理_模板引擎和vue区别

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

       

     

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

今天的文章
模板引擎的实现原理_模板引擎和vue区别分享到此就结束了,感谢您的阅读。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/80644.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注