java ssm框架整合(书籍管理系统)
整体框架配置:
controller包:BookController
package com.msy.controller;
import com.msy.pojo.Book;
import com.msy.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;
/**
* @date 2020/10/12 - 21:10
*/
@Controller
@RequestMapping("/book")
public class BookController {
// controller调用service层
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
//跳转到查询所有书籍界面并且执行查询书籍操作
@RequestMapping("/all")
public String list(Model model){
List<Book> lists = bookService.findBook();
model.addAttribute("list", lists);
return "allbook";
}
//跳转到添加书籍页面
@RequestMapping("/toAddBook")
public String toAddBook(){
return "AddBook";
}
//添加书籍操作
@RequestMapping("/addBook")
public String AddBook(Book book){
bookService.insertBook(book);
return "redirect:/book/all";
}
//跳转到修改书籍页面
@RequestMapping("/toUpdateBook")
public String toUpdateBook(int id,Model model){
Book qboods = bookService.findBookById(id);
model.addAttribute("qbook", qboods);
return "UpdateBooks";
}
//执行修改书籍操作
@RequestMapping("/UpdateBook")
public String UpdateBook(Book book){
System.out.println("update=>"+book);
bookService.updateBook(book);
return "redirect:/book/all";
}
//执行删除书籍操作
@RequestMapping("/del/{bookId}")
public String UpdateBook(@PathVariable("bookId") int id){
bookService.deleteBookById(id);
return "redirect:/book/all";
}
//执行搜索书籍操作
@RequestMapping("/findBookByName")
public String findBookName(String findBookName,Model model){
Book book = bookService.findBookByName(findBookName);
System.out.println(findBookName);
List<Book> lists = new ArrayList<>();
lists.add(book);
if (book == null) {
lists = bookService.findBook();
model.addAttribute("error", "未查到书籍");
}
model.addAttribute("list", lists);
return "allbook";
}
}
Dao包:BookMapper
package com.msy.dao;
import com.msy.pojo.Book;
import java.util.List;
/**
* @date 2020/10/12 - 15:41
*/
public interface BookMapper {
//增加一本书
int insertBook(Book book);
//删除一本书
int deleteBookById(int bookId);
//更新一本书
int updateBook(Book book);
//查询一本书
Book findBookById(int bookId);
//查询全部的书
List<Book> findBook();
//搜索书名
Book findBookByName(String bookName);
}
dao中xml的配置:BookMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.msy.dao.BookMapper">
<insert id="insertBook" parameterType="Book">
insert into ssmbuild.books (bookName, bookCounts, detail) values (#{bookName},#{bookCounts},#{detail});
</insert>
<delete id="deleteBookById" parameterType="int">
delete from ssmbuild.books where bookID = #{bookId}
</delete>
<update id="updateBook" parameterType="Book">
update ssmbuild.books
set bookName = #{bookName},bookCounts=#{bookCounts},detail=#{detail}
where bookID = #{bookID};
</update>
<select id="findBookById" parameterType="int" resultType="Book">
select * from ssmbuild.books where bookID = #{bookID}
</select>
<select id="findBook" resultType="Book">
select * from ssmbuild.books
</select>
<select id="findBookByName" resultType="Book">
select * from ssmbuild.books where bookName = #{bookName}
</select>
</mapper>
pojo包:Book
package com.msy.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @date 2020/10/12 - 15:41
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
service包:BookService
package com.msy.service;
import com.msy.pojo.Book;
import java.util.List;
/**
* @date 2020/10/12 - 16:38
*/
public interface BookService {
//增加一本书
int insertBook(Book book);
//删除一本书
int deleteBookById(int bookId);
//更新一本书
int updateBook(Book book);
//查询一本书
Book findBookById(int bookId);
//查询全部的书
List<Book> findBook();
//搜索书名
Book findBookByName(String bookName);
}
BookServiceImpl
package com.msy.service;
import com.msy.dao.BookMapper;
import com.msy.pojo.Book;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @date 2020/10/12 - 16:39
*/
public class BookServiceImpl implements BookService {
//spring注入
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
@Override
public int insertBook(Book book) {
return bookMapper.insertBook(book);
}
@Override
public int deleteBookById(int bookId) {
return bookMapper.deleteBookById(bookId);
}
@Override
public int updateBook(Book book) {
return bookMapper.updateBook(book);
}
@Override
public Book findBookById(int bookId) {
return bookMapper.findBookById(bookId);
}
@Override
public List<Book> findBook() {
return bookMapper.findBook();
}
@Override
public Book findBookByName(String bookName) {
return bookMapper.findBookByName(bookName);
}
}
框架整合xml配置:
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--spring主配置文件-->
<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-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:spring-mvc.xml"/>
</beans>
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!--mybatis主配置文件-->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 自动扫描com.msy.pojo下的类型,
使得在后续配置文件Category.xml中使用resultType的时候,
可以直接使用Category,而不必写全com.msy.pojo.Category-->
<typeAliases>
<package name="com.msy.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.msy.dao.BookMapper"></mapper>
</mappers>
</configuration>
database.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=false&useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
spring-dao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--spring整合持久层配置文件 spring中IOC-->
<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">
<!--1.关联数据库配置文件 spring中IOC-->
<context:property-placeholder location="classpath:database.properties"></context:property-placeholder>
<!-- 2.连接池 spring中IOC-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<!-- c3p0连接池的私有属性 -->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!-- 关闭连接后不自动commit -->
<property name="autoCommitOnClose" value="false"/>
<!-- 获取连接超时时间 -->
<property name="checkoutTimeout" value="10000"/>
<!-- 当获取连接失败重试次数 -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!-- 3.SQLSessionFactory
SqlSessionFactory是MyBatis中的一个重要的对象,它是用来创建SqlSession对象的,而SqlSession用来操作数据库的-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- 绑定mybatis的配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>
<!-- 配置dao接口扫描包,动态的实现了dao接口可以注入到spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<!-- 要扫描的dao包-->
<property name="basePackage" value="com.msy.dao"></property>
</bean>
</beans>
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
https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--1.注解驱动-->
<mvc:annotation-driven/>
<!-- 2.静态资源过滤-->
<mvc:default-servlet-handler/>
<!-- 3.扫描包:controller-->
<context:component-scan base-package="com.msy.controller"/>
<!-- 4.视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
spring-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--spring整合service层配置文件 spring中AOP-->
<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:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 1.扫描service下的包-->
<context:component-scan base-package="com.msy.service"/>
<!--2.将我们的所有业务类,注入到spring,可以通过注解或者xml实现-->
<bean id="BookServiceImpl" class="com.msy.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"></property>
</bean>
<!-- 3.声明式事务配置 spring中AOP -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 4.aop事务支持-->
<!-- <aop:config>-->
<!-- </aop:config>-->
</beans>
测试类
import com.msy.pojo.Book;
import com.msy.service.BookService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @date 2020/10/12 - 21:28
*/
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
BookService bookServiceImpl = (BookService) context.getBean("BookServiceImpl");
for (Book books:bookServiceImpl.findBook()) {
System.out.println(books);
}
}
}
AddBook.jsp
<%--
Created by IntelliJ IDEA.
User: 王富贵
Date: 2020/10/13
Time: 9:22
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>添加书籍</title>
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/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>
<form action="${pageContext.request.contextPath}/book/addBook" method="post">
书籍名称:<input type="text" name="bookName" required><br><br><br>
书籍数量:<input type="text" name="bookCounts" required><br><br><br>
书籍详情:<input type="text" name="detail" required><br><br><br>
<input type="submit" value="添加">
</form>
</body>
</html>
allbook.jsp
<%--
Created by IntelliJ IDEA.
User: 王富贵
Date: 2020/10/12
Time: 21:16
To change this template use File | Settings | File Templates.
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ 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.bootcss.com/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/all">显示全部书籍</a>
</div>
<div class="col-md-8 column">
<form class="from-inline" action="${pageContext.request.contextPath}/book/findBookByName">
<span style="color: red">${error}</span>
<input type="text" name="findBookName" placeholder="请输入书的名字">
<input type="submit" value="查询">
</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="${requestScope.get('list')}">
<tr>
<td>${book.getBookID()}</td>
<td>${book.getBookName()}</td>
<td>${book.getBookCounts()}</td>
<td>${book.getDetail()}</td>
<td>
<a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}">更改</a>
|
<a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
UpdateBooks.jsp
<%--
Created by IntelliJ IDEA.
User: 王富贵
Date: 2020/10/13
Time: 9:54
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改书籍</title>
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/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>
<form action="${pageContext.request.contextPath}/book/UpdateBook" method="post">
<input type="hidden" name="bookID" value="${qbook.bookID}">
书籍名称:<input type="text" name="bookName" value="${qbook.bookName}"><br><br><br>
书籍数量:<input type="text" name="bookCounts"value="${qbook.bookCounts}"><br><br><br>
书籍详情:<input type="text" name="detail" value="${qbook.detail}"><br><br><br>
<input type="submit" value="修改">
</form>
</body>
</html>
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>springmvc</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>springmvc</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过期时间 15分钟-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
index.jsp
<%--
Created by IntelliJ IDEA.
User: 王富贵
Date: 2020/10/12
Time: 20:43
To change this template use File | Settings | File Templates.
--%>
<%@ 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: 4px;
}
</style>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/book/all">来吧,展示</a>
</h3>
</body>
</html>
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.msy</groupId>
<artifactId>ssmbuild</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<!--依赖-->
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
<!--Servlet - JSP -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--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>
<!-- lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
</dependencies>
<!--静态资源导出-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>