通过Thymeleaf实现表白墙案例

一:创建 Maven 项目
二:在main目录下创建 webapp 文件夹;在 webapp 文件夹下创建 WEB-INF文件夹,在WEB-INF文件夹下创建 template 文件夹和 web.xml
通过Thymeleaf实现表白墙案例_第1张图片

三:在 pom.xml 中引入依赖

<dependencies>
        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>3.1.0version>
            <scope>providedscope>
        dependency>

        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.45version>
        dependency>

        
        <dependency>
            <groupId>org.thymeleafgroupId>
            <artifactId>thymeleafartifactId>
            <version>3.0.14.RELEASEversion>
        dependency>
dependencies>

在 web.xml 写入以下代码

DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
     <display-name>Archetype Created Web Applicationdisplay-name>
web-app>

四:创建模板文件

创建 message.html,放到 template 文件夹下。

DOCTYPE html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>表白墙title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .container{
            width: 400px;
            margin: 0 auto;
        }
        h1{
            text-align: center;
            padding: 20px 0;
        }
        p{
            color: #666;
            text-align: center;
            font-size: 14px;
            padding: 10px 0;
        }
        .row{
            height: 40px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        span{
            width: 100px;
            line-height: 40px;
        }
        .edit{
            width: 200px;
            height: 30px;
        }
        .submit{
            width: 304px;
            height: 40px;
            color: white;
            background-color: orange;
            border: none;
        }
    style>
head>
<body>
<div class="container">
      <h1>表白墙h1>
      <p>输入后点击提交, 会将信息显示在表格中p>
      <form action="message" method="POST">
        <div class="row">
          <span class="label">谁: span>
          <input class="edit" type="text" name="from">
        div>
        <div class="row">
          <span class="label">对谁: span>
          <input class="edit" type="text" name="to">
        div>
        <div class="row">
          <span class="label">说什么: span>
          <input class="edit" type="text" name="message">
        div>
        <div class="row">
          <input type="submit" value="提交" class="submit">
        div>
      form>
      <div class="row" th:each="message : ${messages}">
        <span th:text="${message.from}">小猫span><span th:text="${message.to}">小狗
span> 说: <span th:text="${message.message}">span>
      div>
div>
body>
html>

五:初始化模板引擎

创建 ThymeleafConfig 类,并实现 ServletContextListener 接口

@WebListener
public class ThymeleafConfig implements ServletContextListener {
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        // 1.先获取到 context 对象
        ServletContext context = servletContextEvent.getServletContext();
        // 2.创建 TemplateEngine 实例
        TemplateEngine engine = new TemplateEngine();
        // 3.创建 ServletContextTemplateResolver 实例
        ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(context);
        // 4.给 resolver 设置一些属性
        resolver.setCharacterEncoding("utf-8");
        resolver.setPrefix("/WEB_INT/template");
        resolver.setSuffix("/html");
        // 5.关联 resolver 和 engine
        engine.setTemplateResolver(resolver);

        // 6.把 engine 放到 ServletContext 中,以备后面的 Servlet 类使用
        context.setAttribute("engine",engine);
    }

    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}

六:创建连接数据库的 DBUtil 类

// 负责和数据库建立连接
public class DBUtil {
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/Messagewall?characterEncoding=utf8&useSSL=false";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";

    private static DataSource dataSource = null;

    private static DataSource getDataSource(){
        if(dataSource==null){
            dataSource = new MysqlDataSource();
            ((MysqlDataSource)dataSource).setURL(URL);
            ((MysqlDataSource)dataSource).setUser(USERNAME);
            ((MysqlDataSource)dataSource).setPassword(PASSWORD);
        }
        return dataSource;
    }

    public static Connection getConnection(){
        try {
            return getDataSource().getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet){
        try{
            if(resultSet!=null){
                resultSet.close();
            }
            if(statement!=null){
                statement.close();
            }
            if(connection!=null){
                connection.close();
            }
        }catch (SQLException e){
            e.printStackTrace();
        }

    }
}

创建 MessageServlet 类

class Message{
    public String from;
    public String to;
    public String message;
}
@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    private List<Message> load() {
        List<Message> messageList = new ArrayList<Message>();
        // 1.和数据库建立连接
        Connection connection = DBUtil.getConnection();
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try{
            // 2.拼装 SQL
            String sql = "select * from messages";
            statement = connection.prepareStatement(sql);
            // 3.执行 SQL
            resultSet = statement.executeQuery();
            // 4.遍历结果集合
            while (resultSet.next()){
                Message message = new Message();
                message.from = resultSet.getString("from");
                message.to = resultSet.getString("to");
                message.message = resultSet.getString("message");
                messageList.add(message);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            // 5.释放必要的资源
            DBUtil.close(connection,statement,resultSet);
        }
        return messageList;
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        // 1. 从数据库读取数据
        List<Message> messageList = load();
        // 2. 对页面进行渲染
        ServletContext context = getServletContext();
        TemplateEngine engine = (TemplateEngine) context.getAttribute("engine");
        WebContext webContext = new WebContext(req,resp,context);
        webContext.setVariable("messages",messageList);
        engine.process("message",webContext,resp.getWriter());
    }



    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Message message = new Message();
        message.from = req.getParameter("from");
        message.to = req.getParameter("to");
        message.message = req.getParameter("message");

        save(message);
        resp.sendRedirect("message");
    }

    private void save(Message message) {
        // 1.和数据库建立连接
        Connection connection = DBUtil.getConnection();
        PreparedStatement statement = null;
        try {
            // 2.拼装SQL
            String sql = "insert into messages value(?,?,?)";
            statement = connection.prepareStatement(sql);

            statement.setString(1,message.from);
            statement.setString(2,message.to);
            statement.setString(3,message.message);
            // 3.执行SQL
            statement.executeUpdate();

        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,statement,null);
        }
    }
}

七:测试
通过Thymeleaf实现表白墙案例_第2张图片

你可能感兴趣的:(JavaWeb,tomcat)