web尝试---信箱

news2024/9/27 7:24:28

功能

写信(增加)+读信(显示所有信件)

目录结构

数据库设计

刚开始设计了主键为id,但是后来不想用id这个属性了,但是代码写完了很麻烦不想改了。

感觉我这个id属性设置的简直多余!!!!

id重复了没法添加,但是用户怎么知道写的id是否重复呢,他也不应该看数据库挑一个没用过的id啊。

后端代码

dao层

里面有两个方法:增加+查询所有

package com.xx.note.dao;import com.xx.note.pojo.Note;
import com.xx.note.utils.JdbcBase;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class NoteDao {
    public void addNote(Note note) {
        try {
            Connection c = JdbcBase.getConnection();
            String sql = "INSERT INTO note (id, name, content, date) VALUES (?, ?, ?, ?)";
            PreparedStatement ps = c.prepareStatement(sql);
            ps.setInt(1, note.getId());
            ps.setString(2, note.getName());
            ps.setString(3, note.getContent());
            ps.setDate(4, note.getDate());

            ps.executeUpdate();

            ps.close();
            c.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public List<Note> getAllNotes() {
        List<Note> noteList = new ArrayList<>();
        try {
            Connection c = JdbcBase.getConnection();
            String sql = "SELECT * FROM note";
            PreparedStatement ps = c.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();

            while (rs.next()) {
                Note note = new Note();
                note.setId(rs.getInt("id"));
                note.setName(rs.getString("name"));
                note.setContent(rs.getString("content"));
                note.setDate(rs.getDate("date"));

                noteList.add(note);
            }

            rs.close();
            ps.close();
            c.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return noteList;
    }
}

pojo实体

4个属性,对应get,set等等方法,全参构造,空参构造...

package com.xx.note.pojo;

import java.sql.Date;

public class Note {
    private int id;
    private String name;
    private String content;
    private Date date;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public Note(int id, String name, String content, Date date) {
        this.id = id;
        this.name = name;
        this.content = content;
        this.date = date;
    }

    public Note() {
    }

    @Override
    public String toString() {
        return "Note{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", content='" + content + '\'' +
                ", date=" + date +
                '}';
    }
}

service层

调用dao层的方法

package com.xx.note.service;

import com.xx.note.dao.NoteDao;
import com.xx.note.pojo.Note;

import java.util.List;

public class NoteService {
    private NoteDao noteDao = new NoteDao();

    public void addNote(Note note) {
        noteDao.addNote(note);
    }

    public List<Note> getAllNotes() {
        return noteDao.getAllNotes();
    }
}

servlet

有读信和写信两个功能,写了两个servlet。

NoteReadServlet

package com.xx.note.servlet;
import com.alibaba.fastjson.JSON;
import com.xx.note.pojo.Note;
import com.xx.note.service.NoteService;

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 java.io.IOException;
import java.util.List;

@WebServlet("/read")

public class NoteReadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取笔记列表
        List<Note> notes = new NoteService().getAllNotes(); // 获取笔记的逻辑

        request.setAttribute("notes",notes);
        request.getRequestDispatcher("/read.jsp").forward(request,response);

        //json好使嘿嘿嘿
//        //将对象转换为json字符串
//        String json = JSON.toJSONString(notes);
//        //设置编码格式
//        response.setCharacterEncoding("utf-8");
//        response.getWriter().print(json);
    }
}

 NoteWriteServlet

提交后,提示成功,以html格式打印到网页

package com.xx.note.servlet;
import com.xx.note.pojo.Note;
import com.xx.note.service.NoteService;

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 java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/write")
public class NoteWriteServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        // 获取表单数据
        int id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        String content = request.getParameter("content");
        String dateStr = request.getParameter("date");

        System.out.println("测试一下嘿嘿嘿");

        // 将字符串日期转换为 Date 对象
        Date date = null;
        try {
            date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 这里可以将 Note 对象存入数据库或进行其他处理
        Note note = new Note();
        note.setId(id);
        note.setName(name);
        note.setContent(content);
//        note.setDate((java.sql.Date) date);
        note.setDate(new java.sql.Date(date.getTime()));

        NoteService noteService = new NoteService();
        //调用Service层增加方法(add),增加记录
        noteService.addNote(note);

        // 响应提交结果
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>提交成功啦!!!</h1>");
        out.println("<p>ID: " + note.getId() + "</p>");
        out.println("<p>Name: " + note.getName() + "</p>");
        out.println("<p>Content: " + note.getContent() + "</p>");
        out.println("<p>Date: " + new SimpleDateFormat("yyyy-MM-dd").format(note.getDate()) + "</p>");
        out.println("</body></html>");
    }
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);//Get请求和Post请求的处理是一样的,所以把request、response转交给Post方法就好
    }
}

utils工具类

放数据库驱动的几行代码

package com.xx.note.utils;

import com.xx.note.pojo.Note;
import com.xx.note.service.NoteService;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;

public class JdbcBase {
    public static String DBDRIVER = "com.mysql.jdbc.Driver";
    public static String DBURL = "jdbc:mysql://localhost:3306/note?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&autoReconnect=true&failOverReadOnly=false&allowPublicKeyRetrieval=true";
    public static String DBUSER = "root";
    public static String PASSWORD = "123456";
    public static Connection getConnection() throws Exception {
        Class.forName(DBDRIVER);
        return DriverManager.getConnection(DBURL, DBUSER, PASSWORD);
    }
    public static void main(String[] args) {
        try {
            Connection conn = JdbcBase.getConnection();
            System.out.println("数据库连接成功!!!");
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("数据库连接失败!!!");
        }
//        测试方法1好用
//        System.out.println(new NoteService().getAllNotes());
//        测试方法2是否好用
//        new NoteService().addNote(new Note());

    }
}

前端代码

用的jsp

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: 86158
  Date: 2024/7/10
  Time: 10:09
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>来自星星的信箱📫</title>
<%--    <link rel="stylesheet" type="text/css" href="css/index.css"/>--%>
    <style>
        a{
            text-decoration: none;
        }
        a:hover{
            text-decoration: none;
        }
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Poppins', sans-serif;
        }
        .container {
            background: #ffbdc9;
            width: 100%;
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        nav {
            background: #fff;
            border-radius: 50px;
            padding: 10px;
            box-shadow: 0 25px 20px -20px rgba(0, 0, 0, 0.4);
        }
        nav ul li {
            list-style: none;
            display: inline-block;
            padding: 13px 35px;
            margin: 10px;
            font-size: 18px;
            font-weight: 500;
            color: #777;
            cursor: pointer;
            position: relative;
            z-index: 2;
            transition: color 0.5s;
        }
        nav ul li::after {
            content: '';
            background: #f44566;
            width: 100%;
            height: 100%;
            border-radius: 30px;
            position: absolute;
            top: 100%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: -1;
            opacity: 0;
            transition: top 0.5s,opacity 0.5s;
        }
        nav ul li:hover{
            color: #fff;
        }
        nav ul li:hover::after{
            top: 50%;
            opacity: 1;
        }
    </style>

</head>

<body>
<%--<div class="bg">--%>
<div class="container">
    <nav>
        <ul>
            <li><a href="read">读信</a></li>
            <li><a href="loveheart.jsp">💗</a></li>
            <li><a href="write.jsp">写信</a></li>
        </ul>
    </nav>
</div>
<%--</div>--%>

</body>

</html>

read.jsp 

<%--
  Created by IntelliJ IDEA.
  User: 86158
  Date: 2024/7/12
  Time: 12:57
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<%@ page import="java.util.List" %>
<%@ page import="com.xx.note.pojo.Note" %>
<html>
<head>
    <title>read</title>
    <style>
        table {
            border-collapse: collapse;
            margin: auto
        }
        table, td, th {
            border: 1px solid black;
        }
    </style>
</head>
<body>
<table>
    <tr>
        <th>寄信人</th>
        <th>内容</th>
        <th>日期</th>
    </tr>
    <c:forEach items="${notes}" var="note">
        <tr>
            <td>${note.name}</td>
            <td>${note.content}</td>
            <td>${note.date}</td>
        </tr>
    </c:forEach>
</table>

</body>
</html>

write.jsp 

注意form表单的action路径写完整。

<%--
  Created by IntelliJ IDEA.
  User: 86158
  Date: 2024/7/12
  Time: 12:57
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>write</title>
</head>
<body>
<form method="post" action="/node/write">
    <label for="id">ID:</label>
    <input type="number" id="id" name="id" required><br><br>

    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required><br><br>

    <label for="content">Content:</label><br>
    <textarea id="content" name="content" rows="4" cols="50" required></textarea><br><br>

    <label for="date">Date:</label>
    <input type="date" id="date" name="date" required><br><br>

    <input type="submit" value="提交信息">
</form>
</body>
</html>

loveheart.jsp

爱写啥写啥

效果展示

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2089470.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

传知代码-MSA+抑郁症模型总结(三)(论文复现)

代码以及视频讲解 本文所涉及所有资源均在传知代码平台可获取 热门研究领域&#xff1a;情感计算的横向发展 随着社交网络的不断发展&#xff0c;近年来出现了多模态数据的热潮。越来越多的用户采用媒体形式的组合&#xff08;例如文本加图像、文本加歌曲、文本加视频等&…

TypeScript(TS) 自定义绑定快捷键

有很多软件中都可以让用户自定义快捷键 如微信中的快捷键&#xff1a; 思路&#xff1a; 1. 将快捷键分为两部分&#xff1a; a. 主要的键 shift, ctrl, alt, command&#xff1b; b. 非主要的键 字母键、数字键等&#xff1b; 2. 键盘按下事件&#xff1a;比较按键和绑定…

Echarts关系图特效实现

全屏展示 鼠标经过高亮展示 点击其他节点&#xff0c;加载其他节点数据 这个主要利用了echarts的关系图配置。因为需要将相同类型的数据放一起&#xff0c;所以不能实用引力图&#xff0c;引力图虽然效果比较好&#xff0c;而且有动画&#xff0c;但是无法根据同一类型的东西在…

快递时效新视角:‌批量分析派件与签收策略

在快递行业日益竞争的今天&#xff0c;‌时效成为了衡量快递服务质量的重要指标之一。‌对于商家和消费者而言&#xff0c;‌了解快递从到达最后站点到派件以及签收的时效&#xff0c;‌对于优化物流流程、‌提升客户体验具有重要意义。‌本文将介绍如何利用快递批量查询高手软…

17-18 - make 中的路径搜索

---- 整理自狄泰软件唐佐林老师课程 文章目录 1. 常用的源码管理方式1.1 特殊的预定义变量 VPATH&#xff08;全大写&#xff09;1.2 make 对于 VPATH 值的处理方式1.3 vpath&#xff08;全小写&#xff09; 2. 常见问题2.1 问题 12.2 问题 2 1. 常用的源码管理方式 项目中的 …

【化学方程式配平 / 3】

题目 代码 #include <bits/stdc.h> using namespace std; const double eps 1e-8; unordered_map<string, int> e; int eidx, midx; //eidx 元素数&#xff0c; midx 物质数 double matrix[45][45]; int q; bool check_alpha(char c) {if(c > a && c …

这一届单机游戏玩家,都在用云电脑玩《黑神话悟空》

文 | 智能相对论 作者 | 陈泊丞 周五下班&#xff0c;上号玩游戏&#xff0c;突然发现&#xff0c;之前因为电脑配置跟不上&#xff0c;“A”了大半年的游戏亲友竟然在线&#xff1f;&#xff01; “哟&#xff0c;终于舍得配电脑了&#xff1f;&#xff01;”我发消息问道。…

RedisTemplate集成+封装RedisUtil

文章目录 1.项目搭建1.创建一个redis模块2.调整pom.xml&#xff0c;使其成为单独的模块1.sun-common-redis的pom.xml 取消parent2.sun-common的pom.xml 取消对redis模块的管理3.sun-frame的pom.xml 增加对redis模块的管理4.关于只在modules中配置子模块&#xff0c;但是子模块没…

每日OJ_牛客_数据库连接池(简单模拟)

目录 牛客_数据库连接池&#xff08;简单模拟&#xff09; 解析代码 牛客_数据库连接池&#xff08;简单模拟&#xff09; 数据库连接池__牛客网 解析代码 题目解析&#xff1a; 服务器后台访问数据库时&#xff0c;需要先连上数据库&#xff0c;而为了连上数据库&#xf…

数盟IOS端可信ID

一、基本情况介绍 数盟IOS端可信ID介绍页: 数字联盟 数盟号称是还原出原生的IDFA, 但是苹果官网这么介绍&#xff1a; 用户开启跟踪允许跟踪后&#xff0c;APP才可以请求获取IDFA&#xff0c;且用户交互界面允许后&#xff0c;APP才能获取到IDFA. 官网给出的基本架构&#xf…

文章改写神器哪个好用?4款好评不断!

在内容创作中改写文章是少不了的工作&#xff0c;而想要高效率快速的完成改写我们是需要讲究下方法。随着文章改写神器的出现&#xff0c;它已成为了许多创作者在改写文章过程中的得力助手。那么&#xff0c;在众多的选择中&#xff0c;哪些文章改写神器真正好用呢&#xff1f;…

Django+Vue花卉商城系统的设计与实现

目录 1 项目介绍2 项目截图3 核心代码3.1 需要的环境3.2 Django接口层3.3 实体类3.4 config.ini3.5 启动类3.5 Vue 4 数据库表设计5 文档参考6 计算机毕设选题推荐7 源码获取 1 项目介绍 博主个人介绍&#xff1a;CSDN认证博客专家&#xff0c;CSDN平台Java领域优质创作者&…

小王陪您考系统规划与管理师之监督管理必考知识点

监督管理必备 1、风险监督的基本方法 风险评估风险审计定期的风险评审差异和趋势分析技术的绩效评估预留管理 2、服务质量的特性 安全性&#xff1a;保密性、完成性、可用性可靠性&#xff08;练完有追吻&#xff09;&#xff1a;连续性、完备性、有效性、可追溯性、稳定性…

C++中的异常处理与资源管理

前言 在软件开发中&#xff0c;异常处理是确保程序健壮性和可靠性的关键机制之一。同时&#xff0c;资源管理也是至关重要的&#xff0c;尤其是在C这样的语言中&#xff0c;手动管理资源的需求较高。本文将探讨C中的异常处理机制以及如何有效地管理资源&#xff0c;以避免资源…

【Python机器学习】NLP词频背后的含义——距离和相似度

我们可以使用相似度评分&#xff08;和距离&#xff09;&#xff0c;根据两篇文档的表示向量间的相似度&#xff08;或距离&#xff09;来判断文档间有多相似。 我们可以使用相似度评分&#xff08;和举例&#xff09;来查看LSA主题模型与高维TF-IDF模型之间的一致性。在去掉了…

网络模型及协议介绍

一.OSI七层模型 OSI Open System Interconnect 开放系统互连模型 以前不同厂家所生产的网络设备的标准是不同的&#xff0c;所以为了统一生产规范就制定了OSI这个生产模型。 作用&#xff1a;降低网络进行数据通信复杂度 这个模型的作用第一降低数据通信的复杂度&#xff…

时序预测 | 基于VMD-SSA-LSSVM+LSTM多变量时间序列预测模型(Matlab)

目录 效果一览基本介绍程序设计参考资料 效果一览 基本介绍 旧时回忆&#xff0c;独此一家。基于VMD-SSA-LSSVMLSTM多变量时间序列预测模型&#xff08;Matlab&#xff09; ——————组合模型预测结果—————————— 预测绝对平均误差MAE LSTM VMDSSALSSVM 组合模型 …

Tomcat10安装

Tomcat下载 进入官网下载https://tomcat.apache.org 注意tomcat版本和Java版本的对应关系&#xff1a; 配置好JAVA_HOME 安装tomcat前&#xff0c;需要先配置好JAVA_HOME&#xff0c;因为tomcat启动时候默认会找环境里面的JAVA_HOME&#xff0c;这里选择的Java版本是java1…

桥接与NET

仔细看看下面两幅图 net模式&#xff0c;就是在你的Windows电脑&#xff08;假设叫A电脑&#xff09;的网络基础上&#xff0c;再生成一个子网络&#xff0c;ip的前两位默认就是192.168&#xff0c;然后第三位是随机&#xff0c;第四位是自己可以手动设置的。使用这种模式唯一的…

112. 路径总和(递归法)

目录 一&#xff1a;题目&#xff1a; 二&#xff1a;代码&#xff1a; 三&#xff1a;结果&#xff1a; 一&#xff1a;题目&#xff1a; 给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径&#xff0c;这条路径上所…