一、新建一个Maven项目,配置pom.xml添加依赖
<dependency>
<groupId>mariadb</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>1.8.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
用build标签添加插件:
<build>
<plugins>
<!-- define the project compile level -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- 添加tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
<port>8080</port>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
</plugins>
</build>
二、在main下添加webapp目录,在webapp下添加WEB-INF,在WEB-INF下添加pages,web.xml。pages里编写页面。如图所示:
目录结构.png
其中test.jsp是测试项
web.xml如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
</web-app>
在其中添加servlet,DispatcherServlet(分发)及路径上下文标签
完整web.xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>aaa</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>aaa</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter> //中文过滤器
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
三、在resource目录下添加spring-mvc.xml,mybatis.xml(数据库配置文件)
spring-mvc.xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<!--<property name="suffix" value=".jsp"></property>-->
</bean>
<!--配置缺省的servlet处理器,静态资源可以直接被访问-->
<mvc:default-servlet-handler></mvc:default-servlet-handler>
<!--上下文的组件扫描-->
<context:component-scan base-package="com.qianfeng.controller"></context:component-scan>
<!--配置注解驱动-->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
mybatis.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节点
里面有配置信息 分别是环境和映射
其中环境里有datasource,里面有我们熟悉的连接数据库的四个字符串
-->
<configuration>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="org.mariadb.jdbc.Driver"/>
<property name="url" value="jdbc:mariadb://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="yutong19970820"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="BookMapper.xml"/>
</mappers>
</configuration>
四、再在resource目录下新建一个BookMapper.xml,在其中编写SQL语句进行数据库操作
<?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,
每个方法对应自己的sql语句,每个sql语句对应有一个id
整个项目中所有的namespace.id必须是唯一的
resultType:结果的数据类型
-->
<mapper namespace="BookMapper">
<!--查询全部图书(进行展示)-->
<select id="selectAllBook" resultType="com.qianfeng.bean.BookBean">
select * from springmvcbook
</select>
<!--根据id获得这本书的所有信息(在更新页面展示出旧信息)-->
<select id="getBookById" resultType="com.qianfeng.bean.BookBean">
select * from springmvcbook where id=#{id}
</select>
<!--更新图书-->
<select id="updataBook" resultType="com.qianfeng.bean.BookBean">
update springmvcbook set name=#{name},price=#{price} where id=#{id}
</select>
<!--根据id删除图书-->
<select id="deleteBookById" resultType="com.qianfeng.bean.BookBean">
delete from springmvcbook where id=#{id}
</select>
<!--增加新图书-->
<select id="addBook" resultType="com.qianfeng.bean.BookBean">
insert into springmvcbook values (default ,#{name},#{price})
</select>
<!--获取图书数量
<select id="getBookCount" resultType="int">
select count (1) from springmvcbook
</select>-->
</mapper>
五、编写dao层,在dao层中先找到mybatis.xml,启动数据库,然后mybatis.xml中的 <mapper resource="BookMapper.xml"/>找到BookMapper.xml进行SQL操作。其中创建SqlSessionFactory对象,用SqlSessionFactory对象的openSession()方法来得到一个SqlSession对象以及关闭session代码几乎类似重复。
public class BookDao {
public List<BookBean> getAllBook(){
try {
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
SqlSession session = sf.openSession(true);
List<BookBean> list = session.selectList("BookMapper.selectAllBook");
if (session!=null){
session.close();
session = null;
}
return list;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public BookBean getBookById(int id){
try {
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
SqlSession session = sf.openSession(true);
BookBean bookBean = session.selectOne("BookMapper.getBookById",id);
if (session!=null){
session.close();
session = null;
}
return bookBean;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public int updataBook(BookBean bookBean){
try {
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
SqlSession session = sf.openSession(true);
int i = session.update("BookMapper.updataBook",bookBean);
if (session!=null){
session.close();
session = null;
}
return i;
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
public int deletBookById(int id){
try {
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
SqlSession session = sf.openSession(true);
int i = session.delete("BookMapper.deleteBookById",id);
if (session!=null){
session.close();
session = null;
}
return i;
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
public int addBook(BookBean bookBean){
try {
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
SqlSession session = sf.openSession(true);
int i = session.insert("BookMapper.addBook",bookBean);
if (session!=null){
session.close();
session = null;
}
return i;
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
六、controller层中控制器的编写,用@Controller注解
(1)@RequestMapping("/book")因为是浏览器请求/book去页面,因此用@RequestMapping
(2)@GetMapping("/getBookById/{id}"),@GetMapping("/deleteById/{id}"),@GetMapping("/toAddPage")都用了路径传参,所以用@GetMapping
(3)@PostMapping("/updata"),@PostMapping("/add")其中/updata,/add都是在form表单中用post提交请求,所以用@PostMapping
@Controller
public class BookController {
private BookService bookService = new BookService();
@RequestMapping("/book")
public String getAllBook(HttpSession session){
List<BookBean> list = bookService.getAllBook();
session.setAttribute("list",list);
return "book.jsp";
}
@GetMapping("/getBookById/{id}")
public String getBookById(@PathVariable int id,HttpSession session){
BookBean bookBean = bookService.getBookById(id);
session.setAttribute("book",bookBean);
return "updata.jsp";
}
@PostMapping("/updata")
public String updataBook(BookBean bookBean){
Boolean flg = bookService.updataBook(bookBean);
if(flg){
return "redirect:/book";
}
return "";
}
@GetMapping("/deleteById/{id}")
public String deleteById(@PathVariable int id){
Boolean flg = bookService.deletBookById(id);
if(flg){
return "redirect:/book";
}
return "";
}
@GetMapping("/toAddPage")
public ModelAndView toAddPage(){
return new ModelAndView("add.jsp");
}
@PostMapping("/add")
public String addBook(BookBean bookBean){
Boolean flg = bookService.addBook(bookBean);
if(flg){
return "redirect:/book";
}
return "";
}
}
七、编写主页展示页面book.jsp,更新页面updata.jsp,添加页面add.jsp
book.jsp:
<body>
<c:if test="${list!=null}">
<table border="1" align="center" width="80%">
<tr>
<th>编号</th>
<th>书名</th>
<th>价格</th>
<th>其他</th>
</tr>
<c:forEach items="${list}" var="item">
<tr>
<td align="center">${item.id}</td>
<td align="center">${item.name}</td>
<td align="center">${item.price}</td>
<td><a href="/getBookById/${item.id}">修改</a>
<a href="/deleteById/${item.id}">删除</a>
</td>
</tr>
</c:forEach>
</table>
<div>
<button><a href="/toAddPage">添加新书</a></button>
</div>
</c:if>
</body>
updata.jsp:
body>
<div align="center">
<form method="post" action="/updata">
编号:<input type="text" name="id" value="${book.id}" readonly="readonly"><br>
书名:<input type="text" name="name" value="${book.name}" ><br>
价格:<input type="text" name="price" value="${book.price}" ><br>
<input type="submit" value="更新">
</form>
</div>
add.jsp:
<body>
<form method="post" action="/add">
书名:<input type="text" name="name"><br>
价格:<input type="text" name="price"><br>
<input type="submit">
</form>
</body>
八、效果图如下:
项目完整目录结构:
完整项目结构图.png
页面效果图:
图书系统主页.png
修改页面.png
添加页面.png