编写一个基于Mybatis的留言本
时间: 2024-01-13 16:05:49 浏览: 226
MyBatis框架学习源码
留言本是一个常见的Web应用程序,可以让用户在网站上留下信息或评论。下面是一个基于MyBatis的留言本的示例代码:
1. 创建数据库表message
```
CREATE TABLE message (
id INT(11) NOT NULL AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
content TEXT NOT NULL,
create_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
);
```
2. 创建Message实体类
```
public class Message {
private int id;
private String username;
private String content;
private Date createTime;
// 省略getter和setter方法
}
```
3. 创建MessageMapper接口
```
public interface MessageMapper {
int addMessage(Message message);
List<Message> getAllMessages();
}
```
4. 创建MessageMapper.xml文件
```
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="MessageMapper">
<insert id="addMessage" parameterType="Message">
INSERT INTO message(username, content, create_time) VALUES(#{username}, #{content}, #{createTime})
</insert>
<select id="getAllMessages" resultType="Message">
SELECT * FROM message ORDER BY create_time DESC
</select>
</mapper>
```
5. 创建MessageDao类
```
public class MessageDao {
private SqlSessionFactory sqlSessionFactory;
public MessageDao() {
sqlSessionFactory = MyBatisUtil.getSqlSessionFactory();
}
public void addMessage(Message message) {
try (SqlSession session = sqlSessionFactory.openSession()) {
MessageMapper mapper = session.getMapper(MessageMapper.class);
mapper.addMessage(message);
session.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<Message> getAllMessages() {
List<Message> messages = null;
try (SqlSession session = sqlSessionFactory.openSession()) {
MessageMapper mapper = session.getMapper(MessageMapper.class);
messages = mapper.getAllMessages();
} catch (Exception e) {
e.printStackTrace();
}
return messages;
}
}
```
6. 创建MyBatisUtil类
```
public class MyBatisUtil {
private static SqlSessionFactory sqlSessionFactory;
static {
try (InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml")) {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
}
```
7. 创建MessageServlet类
```
public class MessageServlet extends HttpServlet {
private MessageDao messageDao;
@Override
public void init() throws ServletException {
super.init();
messageDao = new MessageDao();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<Message> messages = messageDao.getAllMessages();
req.setAttribute("messages", messages);
req.getRequestDispatcher("message.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String content = req.getParameter("content");
Message message = new Message();
message.setUsername(username);
message.setContent(content);
message.setCreateTime(new Date());
messageDao.addMessage(message);
resp.sendRedirect(req.getContextPath() + "/message");
}
}
```
8. 创建message.jsp页面
```
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>留言本</title>
</head>
<body>
<h1>留言本</h1>
<form action="message" method="post">
用户名:<input type="text" name="username"><br>
内容:<textarea name="content" rows="5" cols="50"></textarea><br>
<input type="submit" value="提交">
</form>
<hr>
<h2>留言列表</h2>
<c:forEach items="${messages}" var="message">
<p>
${message.username}:<br>
${message.content}<br>
${message.createTime}
</p>
</c:forEach>
</body>
</html>
```
通过以上步骤,我们就可以创建一个基于MyBatis的留言本应用程序。用户可以在网页上留言,留言信息将被存储在数据库中,并可以查看所有留言。
阅读全文