功能
写信(增加)+读信(显示所有信件)
目录结构
数据库设计
刚开始设计了主键为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>来自星星的信箱
标签:web,note,java,String,id,---,import,信箱,public
From: https://blog.csdn.net/yesyesyes_yes/article/details/141678235