web尝试---信箱

栀栀栀 2024-10-04 09:03:02 阅读 70

功能

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

目录结构

数据库设计

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

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

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

后端代码

dao层

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

<code>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 + '\'' +code>

", content='" + content + '\'' +code>

", 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")code>

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" %>code>

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8"/>code>

<title>来自星星的信箱📫</title>

<%-- <link rel="stylesheet" type="text/css" href="css/index.css"/>--%>code>

<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">--%>code>

<div class="container">code>

<nav>

<ul>

<li><a href="read">读信</a></li>code>

<li><a href="loveheart.jsp">💗</a></li>code>

<li><a href="write.jsp">写信</a></li>code>

</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" %>code>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>code>

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>code>

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>code>

<%@ page import="java.util.List" %>code>

<%@ page import="com.xx.note.pojo.Note" %>code>

<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">code>

<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" %>code>

<html>

<head>

<title>write</title>

</head>

<body>

<form method="post" action="/node/write">code>

<label for="id">ID:</label>code>

<input type="number" id="id" name="id" required><br><br>code>

<label for="name">Name:</label>code>

<input type="text" id="name" name="name" required><br><br>code>

<label for="content">Content:</label><br>code>

<textarea id="content" name="content" rows="4" cols="50" required></textarea><br><br>code>

<label for="date">Date:</label>code>

<input type="date" id="date" name="date" required><br><br>code>

<input type="submit" value="提交信息">code>

</form>

</body>

</html>

loveheart.jsp

爱写啥写啥

效果展示

 

效果展示

改了一丢丢,粉色系!



声明

本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。