使用SpringMVC+Mybatis完成一个简单的留言板
时间: 2023-06-25 22:06:31 浏览: 968
基于springMVC+mybatis+easyui的留言板源码
好的,下面我将为您简单介绍如何使用SpringMVC和MyBatis完成一个简单的留言板。
1. 环境准备:
- JDK1.8及以上版本
- Tomcat 7及以上版本
- Eclipse或者IntelliJ IDEA开发工具
- Maven
2. 创建项目:
首先,我们可以使用Maven来创建一个基于SpringMVC和MyBatis的Web项目,可以在终端中输入以下命令:
```
mvn archetype:generate -DgroupId=com.example -DartifactId=message-board -DarchetypeArtifactId=maven-archetype-webapp
```
然后按照提示输入相关信息即可生成项目。
3. 添加相关依赖:
在项目的pom.xml文件中添加以下依赖:
```xml
<!-- SpringMVC依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.10</version>
</dependency>
<!-- MyBatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
<!-- JSP标签库jar包 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Servlet依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- Junit测试依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
```
4. 配置数据源和MyBatis:
在项目的src/main/resources目录下创建一个名为application.properties的文件,并添加以下内容:
```properties
# 数据源配置
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/message_board?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=
# MyBatis配置
mybatis.type-aliases-package=com.example.messageboard.entity
mybatis.mapper-locations=classpath:mapper/*.xml
```
其中,我们需要将数据库连接信息配置好,这里使用的是MySQL数据库。
在src/main/resource目录下创建一个名为mybatis-config.xml的文件,并添加以下内容:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="autoMappingBehavior" value="PARTIAL"/>
<setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25"/>
<setting name="defaultFetchSize" value="100"/>
</settings>
</configuration>
```
5. 编写实体类和Mapper:
在src/main/java目录下创建一个名为com.example.messageboard.entity的包,并在该包下创建一个名为Message的实体类:
```java
public class Message {
private int id;
private String content;
private String author;
private Date createTime;
// getter和setter方法
// ...
}
```
在src/main/java目录下创建一个名为com.example.messageboard.mapper的包,并在该包下创建一个名为MessageMapper的Mapper接口:
```java
public interface MessageMapper {
List<Message> findAll();
void save(Message message);
}
```
在src/main/resources/mapper目录下创建一个名为MessageMapper.xml的文件,并添加以下内容:
```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="com.example.messageboard.mapper.MessageMapper">
<resultMap id="messageMap" type="Message">
<id column="id" property="id"/>
<result column="content" property="content"/>
<result column="author" property="author"/>
<result column="create_time" property="createTime"/>
</resultMap>
<select id="findAll" resultMap="messageMap">
select * from message
</select>
<insert id="save" parameterType="Message">
insert into message (content, author, create_time)
values (#{content}, #{author}, #{createTime})
</insert>
</mapper>
```
6. 编写Controller:
在src/main/java目录下创建一个名为com.example.messageboard.controller的包,并在该包下创建一个名为MessageController的Controller:
```java
@Controller
@RequestMapping("/message")
public class MessageController {
@Autowired
private MessageMapper messageMapper;
@RequestMapping("/list")
public String list(Model model) {
List<Message> messages = messageMapper.findAll();
model.addAttribute("messages", messages);
return "message/list";
}
@RequestMapping("/add")
public String add() {
return "message/add";
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(Message message) {
message.setCreateTime(new Date());
messageMapper.save(message);
return "redirect:/message/list";
}
}
```
7. 编写JSP页面:
在src/main/webapp/WEB-INF/views/message目录下创建一个名为list.jsp的文件,并添加以下内容:
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>留言列表</title>
</head>
<body>
<table border="1">
<tr>
<th>ID</th>
<th>内容</th>
<th>作者</th>
<th>创建时间</th>
</tr>
<c:forEach items="${messages}" var="message">
<tr>
<td>${message.id}</td>
<td>${message.content}</td>
<td>${message.author}</td>
<td>${message.createTime}</td>
</tr>
</c:forEach>
</table>
<a href="/message/add">添加留言</a>
</body>
</html>
```
在src/main/webapp/WEB-INF/views/message目录下创建一个名为add.jsp的文件,并添加以下内容:
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加留言</title>
</head>
<body>
<form action="/message/save" method="post">
<div>
<label>内容:</label>
<input type="text" name="content">
</div>
<div>
<label>作者:</label>
<input type="text" name="author">
</div>
<div>
<button type="submit">提交</button>
</div>
</form>
</body>
</html>
```
8. 配置DispatcherServlet:
在项目的web.xml文件中添加以下配置:
```xml
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
```
在src/main/resources目录下创建一个名为springmvc-servlet.xml的文件,并添加以下内容:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 扫描Controller包 -->
<context:component-scan base-package="com.example.messageboard.controller"/>
<!-- 配置视图解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 配置MyBatis -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${spring.datasource.driverClassName}"/>
<property name="url" value="${spring.datasource.url}"/>
<property name="username" value="${spring.datasource.username}"/>
<property name="password" value="${spring.datasource.password}"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.messageboard.mapper"/>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 开启SpringMVC注解支持 -->
<mvc:annotation-driven/>
</beans>
```
9. 启动项目:
在Eclipse或者IntelliJ IDEA中运行项目,然后在浏览器中访问http://localhost:8080/message/list即可看到留言列表页面,点击添加留言按钮可以添加留言。
阅读全文