引言
这是一个简易SSM整合项目,适合后端入门的练习项目,其中没有太多的业务操作,主要是这个框架,以及编码的顺序,希望大家有所收获
首先需要先配置环境
数据库环境
创建一个存放书籍的数据库表
create database 'ssmbuild';
use 'ssmbuild';
drop table if exists 'books';
create table 'books'(
'bookID' int(10) not null auto_increment comment '书籍ID';
'bookName' VARCHAR(100) NOT NULL COMMENT '书名',
'bookCounts' INT(11) NOT NULL COMMENT '数量',
'detail' VARCHAR(200) NOT NULL COMMENT '描述',
KEY 'bookID' ('bookID')
)engine = innodb default charset = utf8
INSERT INTO 'books'('bookID','bookName','bookCounts','detail')VALUES
(1,'Java',1,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',5,'从进门到进牢');
基本环境创建
新建一个maven项目,FristSSMProject,添加web组件
2.导入相关pom依赖
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!-- MyBatis 和 MyBatis-Spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.13</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.7</version>
</dependency>
<!-- 数据库连接 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.10.1</version>
</dependency>
<!-- Servlet/JSP -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 其他依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency><!-- lombok注解驱动-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version> 1.18.36</version>
</dependency>
</dependencies>
建议JDK版本为11,不然可能会报错
Unsupported class file major version 61 (如果报这个错误就是版本问题)
Maven资源过滤问题
<!-- 静态资源导出问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
创建基本结构(实体层,模型层,业务层,控制层),和配置文件
编译Mybatis配置文件
<?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="LogImpl" value="STDOUT_LOGGING"/>
</settings>
<!-- 配置别名-->
<typeAliases>
<package name="com.lyc.pojo"/>
</typeAliases>
<!-- 环境变量-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="211314"/>
</dataSource>
</environment>
</environments>
<mappers>
</mappers>
</configuration>
注:要将lib包导入依赖
编写对应的数据库实体类
package com.lyc.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
//使用Lombok注解
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
编写对应的模型层(Mapper接口以及对应的XML文件)
BookMapper.java
package com.lyc.mapper;
import com.lyc.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookMapper {
//查询所有书籍
List<Books> queryAllBook();
//根据ID查询书籍
Books queryBookByID(@Param("bookID") int id);
//修改书籍
int updateBook(Books books);
//删除书籍
int deleteBookByID( @Param("bookID") int id);
//增加书籍
int addBook(Books books)
//根据名称查询书籍
Books queryBookByName(@Param("bookName") String bookName);
}
BookMapper.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.lyc.mapper.BookMapper">
<insert id="addBook" parameterType="com.lyc.pojo.Books">
insert into ssmbuild.books(bookName,bookCounts,detail) values (#{bookName},#{bookCounts},#{detail})
</insert>
<update id="updateBook" parameterType="com.lyc.pojo.Books">
update ssmbuild.books set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
where bookID = #{bookID}
</update>
<delete id="deleteBookByID" parameterType="int">
delete from ssmbuild.books where bookID = #{bookID}
</delete>
<select id="queryAllBook" resultType="com.lyc.pojo.Books" >
select * from ssmbuild.books
</select>
<select id="queryBookByID" resultType="com.lyc.pojo.Books">
select * from ssmbuild.books where bookID = #{bookID}
</select>
<select id="queryBookByName" resultType="com.lyc.pojo.Books">
select * from ssmbuild.books where bookName like concat ('%',#{bookName},'%')
</select>
</mapper>
注:不要忘记在Mybatis配置文件中配置mapper映射文件
<mappers>
<mapper resource="com/lyc/mapper/BookMapper.xml"/>
</mappers>
测试数据库是否连接成功
import com.lyc.mapper.BookMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
public class MyTest {
@Test
public void test() throws IOException {
String DataSource = "Mybatis-Config.xml";
InputStream stream = Resources.getResourceAsStream(DataSource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
BookMapper mapper = sqlSession.getMapper(BookMapper.class);
mapper.queryAllBook().forEach(System.out::println);
sqlSession.close();
}
}
测试结果
编写Service层的接口以及实现类
BookService
package com.lyc.service;
import com.lyc.pojo.Books;
import java.util.List;
public interface BookService {
//查询所有书籍
List<Books> queryAllBook();
//根据ID查询书籍
Books queryBookByID( int id);
//修改书籍
int updateBook(Books books);
//删除书籍
int deleteBookByID( int id);
//添加书籍
int addBook(Books books);
//根据名称查询书籍
Books queryBookByName( String bookName);
}
BookServiceImpl.java
package com.lyc.service;
import com.lyc.mapper.BookMapper;
import com.lyc.pojo.Books;
import java.util.List;
public class BookServiceImpl implements BookService{
//service调dao层
//调用dao层的操作,设置一个set接口,方便Spring管理
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
@Override
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
@Override
public Books queryBookByID(int id) {
return bookMapper.queryBookByID(id);
}
@Override
public int updateBook(Books books) {
return bookMapper.updateBook(books);
}
@Override
public int deleteBookByID(int id) {
return bookMapper.deleteBookByID(id);
}
@Override
public int addBook(Books books) {
return bookMapper.addBook(books);
}
@Override
public Books queryBookByName(String bookName) {
return bookMapper.queryBookByName(bookName);
}
}
Spring层
配置Spring整合MyBatis,我们这里数据源使用c3p0连接池;
我们去编写Spring整合Mybatis的相关的配置文件;spring-mapper.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置整合Mybatis-->
<!-- 数据库连接池 -->
<!-- 数据库连接池
dbcp 半自动化操作 不能自动连接
c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面)
-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8"/>
<property name="user" value="root"/>
<property name="password" value="211314"/>
<!-- c3p0的私有属性-->
<!-- 连接池极限值-->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!-- 关闭连接后不自动提交 -->
<property name="autoCommitOnClose" value="false"/>
<!-- 获得连接超时时间-->
<property name="checkoutTimeout" value="10000"/>
<!-- 当获取连接失败次数-->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!--配置SqlsessionFactory 对象-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:applicationContext.xml"/>
</bean>
<!--配置扫描Mapper接口包,动态实现Mapper接口注入到spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.lyc.mapper"/>
</bean>
</beans>
spring整合service层
spring-service.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: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/context
https://www.springframework.org/schema/context/spring-context.xsd">
<import resource="spring-mapper.xml"/>
<!--配置扫描service层的bean-->
<context:component-scan base-package="com.lyc.service"/>
<!-- 将BookServiceImpl注入IOC容器-->
<bean id="BookServiceImpl" class="com.lyc.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
Spring层搞定!Spring就是一个容器
SpringMVC层
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_4_0.xsd"
version="4.0">
<!-- 配置DispatcherServlet-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 过滤器 防止乱码-->
<filter>
<filter-name>EncodingFilter</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>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- session过期时间-->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/cache/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--springMVC核心三要素:处理器映射器,处理器适配器,视图解析器-->
<mvc:annotation-driven/>
<!-- 过滤静态资源 -->
<mvc:default-servlet-handler/>
<!-- 视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 扫描关于web的bean-->
<context:component-scan base-package="com.lyc.controller"/>
</beans>
Spring配置整合文件,applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:spring/spring-mvc.xml"/>
<import resource="classpath:spring/spring-mapper.xml"/>
<import resource="classpath:spring/spring-service.xml"/>
</beans>
配置文件到这就已经配得差不多了,框架已经搭好了,现在去写前端页面和Controller层
首先理清思路:我们要完成增删改查操作,增加,修改,需要两个页面,加上书籍列表展示页面,就只有三个页面
所以项目结构应为
BookController 类编写
package com.lyc.controller;
import com.lyc.pojo.Books;
import com.lyc.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping("/book")
public class BookController {
//service层调dao层
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
//查询全部的书籍,并返回到一个书籍展示页面
@RequestMapping("/allBook")
public String list(Model model){
List<Books> list = bookService.queryAllBook();
model.addAttribute("list",list);
return "allBook";
}
//跳转到增加书籍页面
@RequestMapping("/toAddBook")
public String toAddPaper(){
return "addBook";
}
//添加书籍的请求
@RequestMapping("/addBook")
public String addPaper(Books books){
System.out.println("addBook=>"+books);
bookService.addBook(books);
return "redirect:/book/allBook";//重定向/book/allBook请求,重新查询
}
//跳转到修改页面
@RequestMapping("/toUpdateBook/{id}")
public String toUpdatePaper(Model model,@PathVariable int id){
model.addAttribute("book",bookService.queryBookById(id));
return "updateBook";
}
//修改书籍
@RequestMapping("/updateBook")
public String updateBook(Books books){
bookService.updateBook(books);
return "redirect:/book/allBook";
}
//删除书籍
@RequestMapping("/del/{bookId}")
public String deleteBook(@PathVariable("bookId") int id){
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
//查询书籍
@RequestMapping("/queryBook")
public String queryBook(String queryBookName,Model model){
List<Books> list = new ArrayList<>();
if(queryBookName!=null&&queryBookName!=""){
Books books = bookService.queryBookByName(queryBookName);
list.add(books);
model.addAttribute("list",list);
return "allBook";
}
return "redirect:/book/allBook";
}
}
编写首页Index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
<style>
a{
text-decoration: none;
color: black;
font-size: 18px;
}
h3{
width: 180px;
height: 38px;
margin: 100px auto;
text-align: center;
line-height: 38px;
background: deepskyblue;
border-radius: 15px;
}
</style>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/book/allBook">点击进入列表页</a>
</h3>
</body>
</html>
书籍列表页面 allbook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>书籍列表</title>
<%-- 引入Bootstrap--%>
<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row-clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
欢迎来到我的书屋
<small>书籍列表 -- 显示所有书籍</small>
</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 column">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增书籍</a>
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBook">显示全部</a>
</div>
<div class="col-md-4 column col-md-offset-4">
<form action="${pageContext.request.contextPath}/book/queryBook/${book.bookName}" method="post" class="form-inline" style="float: right">
<input type="text" placeholder="请输入要查询的书籍名称" class="form-control" name="queryBookName" required>
<input type="submit" value="查询" class="btn btn-primary">
</form>
</div>
</div>
<div class="row-clearfix">
<div class="col-md-12 column">
<table class="table table-hover table-striped">
<thead>
<tr>
<th>书籍编号</th>
<th>书籍名称</th>
<th>书籍数量</th>
<th>书籍详情</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach var="book" items="${list}">
<tr>
<td>${book.bookID}</td>
<td>${book.bookName}</td>
<td>${book.bookCounts}</td>
<td>${book.detail}</td>
<td><a href="${pageContext.request.contextPath}/book/toUpdateBook/${book.bookID}">更改</a>
|
<a href="${pageContext.request.contextPath}/book/del/${book.bookID}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
添加书籍页面addBook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>新增书籍</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<%-- 引入Bootstrap--%>
<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row-clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>新增书籍</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/addBook" method="post">
<div class="form-group">
<label for="bkname">书籍名称:</label>
<input type="text" name="bookName" id="bkname" class="form-control" required>
</div>
<div class="form-group">
<label for="bkcounts">书籍数量:</label>
<input type="text" name="bookCounts" id="bkcounts" class="form-control" required>
</div>
<div class="form-group">
<label for="bkdetail">书籍详情:</label>
<input type="text" name="detail" id="bkdetail" class="form-control" required>
</div>
<div class="form-group">
<input type="submit" value="添加" class="form-control">
<input type="reset" value="重置" class="form-control">
</div>
</form>
</div>
</body>
</html>
修改书籍页面 updateBook..jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改信息</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<%-- 引入Bootstrap--%>
<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row-clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>修改信息</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/updateBook" method="post">
<%-- 出现问题:我们提交了修改的SQL请求,但是请求失败,初次考虑,以为是事务问题,配置完毕事务,依旧失败!
查看SQL语句,能否执行成功,:SQL语句执行失败,修改未完成
--%>
<%-- 前端传递隐藏域--%>
<input type="hidden" name="bookID" value="${book.bookID}">
<div class="form-group">
<label for="bkname">书籍名称:</label>
<input type="text" name="bookName" id="bkname" class="form-control" value="${book.bookName}" required>
</div>
<div class="form-group">
<label for="bkcounts">书籍数量:</label>
<input type="text" name="bookCounts" id="bkcounts" class="form-control" value="${book.bookCounts}" required>
</div>
<div class="form-group">
<label for="bkdetail">书籍详情:</label>
<input type="text" name="detail" id="bkdetail" class="form-control" value="${book.detail}" required>
</div>
<div class="form-group">
<input type="submit" value="修改" class="form-control">
</div>
</form>
</div>
</body>
</html>
测试阶段
首页:
书籍列表:
增加:
修改:
查询:
希望对大家有所帮助