结果显示如下:
首选是创建一个实体类LeaveAMessage.java作为留言实体对象
package bean;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* 留言实体类
*
* @author lck100
*/
@Data
public class LeaveAMessage implements Serializable {
private int id;// 留言id
private int userId;// 用户id
private Date date;// 日期
private String title;// 留言标题
private String content;// 留言内容
/**
* 空的构造方法
*/
public LeaveAMessage() {
}
/**
* 带参数的构造方法
*
* @param userId 用户id
* @param date 日期
* @param title 标题
* @param content 内容
*/
public LeaveAMessage(int userId, Date date, String title, String content) {
this.userId = userId;
this.date = date;
this.title = title;
this.content = content;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "LeaveAMessage{" +
"id=" + id +
", userId=" + userId +
", date=" + date +
", title='" + title + '\'' +
", content='" + content + '\'' +
'}';
}
}
接着是创建数据库表
# 留言表
create table leaveAMessage
(
id int primary key not null auto_increment comment 'id编号',
userId int not null comment '用户id编号',
date datetime not null comment '留言发表时间',
title varchar(20) not null comment '留言标题',
content varchar(500) not null comment '留言内容'
)
然后是创建操作数据库留言表的方法:
package dao;
import bean.LeaveAMessage;
import utils.JDBCUtils;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
/**
* 留言dao
*
* @author lck100
*/
public class LeaveAMessageDao {
/**
* 查询留言表中的所有留言
*
* @return 返回所有留言的结果集合
*/
public List<LeaveAMessage> checkAll() {
// 创建一个集合来放置从数据库查询到的所有LeaveAMessage对象
List<LeaveAMessage> list = new ArrayList<>();
try {
// 获取数据库连接对象
Connection connection = JDBCUtils.getConnection();
// 查询语句
String sql = "select id, userid, date, title, content from leaveamessage";
// 创建数据库执行对象
PreparedStatement ps = connection.prepareStatement(sql);
// 获取结果集对象
ResultSet rs = ps.executeQuery();
// 遍历结果集
while (rs.next()) {
// 实例化LeaveAMessage对象
LeaveAMessage lam = new LeaveAMessage();
// 设置留言id
lam.setId(rs.getInt(1));
// 设置用户id
lam.setUserId(rs.getInt(2));
// 设置留言日期
lam.setDate(rs.getDate(3));
// 设置留言标题
lam.setTitle(rs.getString(4));
// 设置留言内容
lam.setContent(rs.getString(5));
// 将留言对象添加到集合中
list.add(lam);
}
// 返回查询到的结果集合
return list;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 插入留言
*
* @param lam 留言对象
* @return 返回受影响行数
*/
public int insertLeaveAMessage(LeaveAMessage lam) {
try {
// 获取数据库连接对象
Connection connection = JDBCUtils.getConnection();
// 数据库语句
String sql = "insert into leaveamessage(userId, date, title, content) values (?,?,?,?);";
// 创建数据库执行对象
PreparedStatement ps = connection.prepareStatement(sql);
// 设置参数
ps.setInt(1, lam.getUserId());
// 需要注意的是,Java的日期格式和数据库的日期格式是不一致的,需要进行转换
ps.setDate(2, Date.valueOf(new SimpleDateFormat("yyyy-MM-dd").format(lam.getDate())));
ps.setString(3, lam.getTitle());
ps.setString(4, lam.getContent());
// 执行插入语句并返回受影响行
int i = ps.executeUpdate();
// 返回受影响行数
return i;
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
}
对写的方法进行简单测试,查看是否能够成功从数据库中查询出来数据。
package dao;
import bean.LeaveAMessage;
import org.junit.Test;
import java.util.Date;
import java.util.List;
public class LeaveAMessageTest {
private LeaveAMessageDao leaveAMessageDao = new LeaveAMessageDao();
/**
* 测试查询所有留言方法
*/
@Test
public void testCheckAll() {
List<LeaveAMessage> list = leaveAMessageDao.checkAll();
for (LeaveAMessage leaveAMessage : list) {
System.out.println(leaveAMessage);
}
}
/**
* 测试插入留言方法
*/
@Test
public void testInsertLeaveAMessage(){
LeaveAMessage leaveAMessage=new LeaveAMessage(1,new Date(),"诗词","人生若只如初见");
int i = leaveAMessageDao.insertLeaveAMessage(leaveAMessage);
System.out.println(i);
}
}
测试成功后,接着往下写:
留言信息显示面板,显示所有的留言信息的messageBoard.jsp
<%@ page import="bean.LeaveAMessage" %>
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>留言板信息</title>
</head>
<body>
<form action="leaveAMessage.jsp" method="get" id="app">
<table border="1">
<caption>所有留言信息</caption>
<tr>
<th>留言人姓名</th>
<th>留言时间</th>
<th>留言标题</th>
<th>留言内容</th>
</tr>
<%
// 获取保存在session中的留言信息
ArrayList<LeaveAMessage> leaveAMessage = (ArrayList) session.getAttribute("leaveAMessage");
for (LeaveAMessage aMessage : leaveAMessage) {
%>
<tr>
<td><%=
session.getAttribute("username")
%>
</td>
<td><%=
aMessage.getDate()
%>
</td>
<td><%=
aMessage.getTitle()
%>
</td>
<td><%=
aMessage.getContent()
%>
</td>
</tr>
<%
}
%>
</table>
<input type="submit" value="留言">
</form>
</body>
</html>
以及写留言的页面leaveMessage.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>留言</title>
</head>
<body>
<form action="leaveAMessageServlet" method="post">
<table>
<caption>填写留言信息</caption>
<tr>
<td>留言标题</td>
<td><input type="text" name="title"></td>
</tr>
<tr>
<td>留言内容</td>
<td><textarea name="content" cols="30" rows="10"></textarea></td>
</tr>
</table>
<br><br>
<input type="submit" value="提交">
<input type="reset" value="重置">
</form>
</body>
</html>
对留言的处理LeaveAMessageServlet.java
package servlet;
import bean.LeaveAMessage;
import dao.LeaveAMessageDao;
import dao.UserDao;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.Serializable;
import java.util.Date;
/**
* 留言Servlet
*
* @author lck100
*/
public class LeaveAMessageServlet extends HttpServlet implements Serializable {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// 设置请求编码
request.setCharacterEncoding("UTF-8");
// 设置响应编码
response.setContentType("UTF-8");
// 获取请求的session
HttpSession session = request.getSession();
// 获取留言标题
String title = request.getParameter("title");
// 获取留言内容
String content = request.getParameter("content");
// 实例化LeaveAMessage对象
LeaveAMessage lam = new LeaveAMessage();
// 设置用户id,用户id通过使用名字用数据库查询得来
lam.setUserId(new UserDao().checkUserByName(session.getAttribute("username").toString()).getId());
// 设置日期,日期为当前日期
lam.setDate(new Date());
// 设置留言标题
lam.setTitle(title);
// 设置留言内容
lam.setContent(content);
// 插入数据到数据库
int i = new LeaveAMessageDao().insertLeaveAMessage(lam);
if (i > 0) {
session.setAttribute("success", "留言成功,点击<a href='messageBoard.jsp'>这里</a>返回主界面");
request.getRequestDispatcher("success.jsp").forward(request, response);
} else {
session.setAttribute("error", "留言失败,点击<a href='leaveAMessage.jsp'>这里</a>返回留言界面");
request.getRequestDispatcher("error.jsp").forward(request, response);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}
和在web.xml中的配置
<!--留言Servlet-->
<servlet>
<servlet-name>LeaveAMessageServlet</servlet-name>
<servlet-class>servlet.LeaveAMessageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LeaveAMessageServlet</servlet-name>
<url-pattern>/leaveAMessageServlet</url-pattern>
</servlet-mapping>