JavaWeb 项目 --- 表白墙 和 在线相册

Posted wwzzzzzzzzz

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaWeb 项目 --- 表白墙 和 在线相册相关的知识,希望对你有一定的参考价值。

文章目录

一. 案例: 表白墙 (使用模板引擎)

1. 首先创建 maven 项目

引入需要的依赖,创建必要的目录


2. 创建好模板文件

<!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>
</head>
<body>
    <form action="confession" method="post">
        <div class="parent">
            <div id="wall">表白墙</div>
            <div id="remind">输入后点击提交,会将信息显示在表格中</div>
            <div class="one"><span class="two">谁:</span><input type="text" class="text" name="from"></div>
            <div class="one"><span class="two">对谁:</span><input type="text" class="text" name="to"></div>
            <div class="one"><span class="two">说什么:</span><input type="text" class="text" name="message"></div>
            <div class="one"><input type="submit" value="提 交" class="press"></div>
            <div class="elem" th:each="message : $messages">
                <span th:text="$message.from">wz</span><span th:text="$message.to">zw</span>说: <span th:text="$message.message">wzz</span>
            </div>
        </div>
    </form>
    
    <style>
        /* 去除浏览器默认样式 */
        * 
            margin: 0;
            padding: 0;
        
        /* 设置总宽度 */
        .parent 
            width: 400px;
            margin: 0 auto;
        
        /* 设置表白墙样式 */
        #wall 
            font-size: 30px;
            font-weight: 700;
            text-align: center;
            margin: 5px;
        
        /* 设置提示信息样式 */
        #remind
            font-size:13px;
            text-align: center;
            color:gray;
            margin: 5px;
        
        /* 设置弹性布局 */
        .one 
            display: flex;
            justify-content: center;
            align-items: center;
            height: 40px;
        
        /* 设置文字内容 */
        .two 
            width: 100px;
            line-height: 40px;
        
        /* 设置输入框 */
        .one .text
            width: 200px;
            height: 20px;
            padding-left: 3px;
        
        /* 提交按钮的设置 */
        .one .press
            width: 304px;
            height: 40px;
            color:white;
            background-color: orange;
            border-radius: 5px;
            border: none;
         
        /* 设置鼠标点击的时候改变颜色 */
        .one .press:active
            background-color: red;
        
        /* 提交之后内容的设置 */
        .elem 
            text-align: center;
            margin: 15px;
        
    </style>
</body>
</html>

3. 使用数据库存储数据.创建一个类用于数据库连接

ConnectionDB

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ConnectionDB 
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/confessionWall2?characterEncoding=utf-8&useSSL=true&serverTimezone=UTC";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "0000";

    private static volatile DataSource dataSource = null;

    public static DataSource getDataSource() 
        if(dataSource == null)
            synchronized (ConnectionDB.class)
                if(dataSource == null) 
                    dataSource = new MysqlDataSource();
                    ((MysqlDataSource) dataSource).setURL(URL);
                    ((MysqlDataSource) dataSource).setUser(USERNAME);
                    ((MysqlDataSource) dataSource).setPassword(PASSWORD);

                
            
        
        return dataSource;

    

    public static Connection getConnection() throws SQLException 
        return getDataSource().getConnection();
    

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


4. 使用 监视器 来初始化 Thymeleaf

ThymeleafConfig
注意加上注解

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

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class ThymeleafConfig implements ServletContextListener 
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) 
        System.out.println("ServletContext 初始化完毕!");
        ServletContext context = servletContextEvent.getServletContext();
        TemplateEngine engine = new TemplateEngine();
        ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(context);
        resolver.setPrefix("/WEB-INF/template/");
        resolver.setSuffix(".html");
        resolver.setCharacterEncoding("utf-8");
        engine.setTemplateResolver(resolver);
        context.setAttribute("engine",engine);
    

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) 

    


5. 编写 Servlet 代码

首先创建一个 Confession

class Confession
    public String from;
    public String to;
    public String message;

① 重写 doGet 方法

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException 
        resp.setContentType("text/html;charset=utf-8");
        List<Confession> list = load();

        TemplateEngine engine = (TemplateEngine) getServletContext().getAttribute("engine");
        WebContext webContext = new WebContext(req,resp,getServletContext());
        webContext.setVariable("messages",list);
        engine.process("confessionwall",webContext, resp.getWriter());
    

② 重写 doPost 方法

        resp.setContentType("text/html;charset=utf-8");
        Confession confession = new Confession();
        confession.from = req.getParameter("from");
        confession.to = req.getParameter("to");
        confession.message = req.getParameter("message");

        save(confession);
        resp.sendRedirect("confession");

③ 实现 load 方法

    private List<Confession> load() 
        List<Confession> list = new ArrayList<>();
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try 
            connection = ConnectionDB.getConnection();
            String sql = "select * from confession";
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            while(resultSet.next())
                Confession confession = new Confession();
                confession.from =resultSet.getString("from");
                confession.to = resultSet.getString("to");
                confession.message = resultSet.getString("message");
                list.add(confession);
            
         catch (SQLException throwables) 
            throwables.printStackTrace();
         finally 
            ConnectionDB.close(connection,statement,resultSet);
        
        return list;
    

④ 实现 save 方法

    private void save(Confession confession) 
        Connection connection = null;
        PreparedStatement statement = null;
        try
            connection = ConnectionDB.getConnection();
            String sql = "insert into confession values (?,?,?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1,confession.from);
            statement.setString(2, confession.to);
            statement.setString(3,confession.message);
            int ret = statement.executeUpdate();
            if(ret == 1)
                System.out.println("插入成功");
            else
                System.out.println("插入失败");
            
         catch (SQLException throwables) 
            throwables.printStackTrace();
         finally 
            ConnectionDB.close(connection,statement,null);
        
    

6. 注意事项

  1. 注意模板引擎

  2. 注意 乱码的情况,要添加utf-8


  3. 用数据库的方法存数据,要先创建好数据库

create database confessionWall2;

use confessionWall2;

create table confession(
    `from` varchar(1024),
    `to` varchar(1024),
    `message` varchar(1024)
);
  1. 还有一些必要的注解也要加上.

7. 部署之后 运行截图

浏览器输入对应的URL
在数据库为空的时候界面如下


在输入几个数据之后 如下

此时的数据库中表的内容

重新部署再进入URL发现数据还是存在.

二. 案例: 在线相册 (使用模板引擎)

1. 首先创建 maven 项目

引入必要的依赖,已经必要的目录

2. 创建好模板文件

image.html

<!DOCTYPE html>
<html lang=<

以上是关于JavaWeb 项目 --- 表白墙 和 在线相册的主要内容,如果未能解决你的问题,请参考以下文章

❤表白❤相册——动态3D图片墙

计算机毕业设计springboot校园表白墙小程序管理系统最新版

也等你 [表白墙] 发布!

制作表白墙,给TA一个惊喜吧

意见汇总

表白生日祝福和3D表白相册