环境:
要求:
MySQL数据库
,Spring
,JavaWeb
及MyBatis
知识,简单的前端知识;完整代码:完整代码下载
创建一个存放书籍数据的数据库表
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,'从进门到进牢');
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
dependency>
<dependency>
<groupId>com.mchangegroupId>
<artifactId>c3p0artifactId>
<version>0.9.5.2version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.2version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.1version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.3.6version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.2.14.RELEASEversion>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.8.13version>
dependency>
dependencies>
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
resources>
build>
com.wang.pojo
com.wang.dao
com.wang.service
com.wang.controller
mybatis-config.xml
(mybatis的核心配置文件)
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
configuration>
applicationContext.xml
(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">
beans>
jdbc.driver=com.mysql.jdbc.Driver
#如果使用的是MySQL8.0+,还需要增加一个时区的配置;
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=
mybatis
核心配置文件
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.wang.pojo"/>
typeAliases>
<mappers>
<mapper class="com.wang.dao.BookMapper"/>
mappers>
configuration>
books
package com.wang.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author Wang
* @date 2021/6/2 0012 19:43
* description 实体类books
*/
@Data
@AllArgsConstructor //有参构造
@NoArgsConstructor //无参构造
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
dao
接口package com.wang.dao;import com.wang.pojo.Books;import org.apache.ibatis.annotations.Param;import org.springframework.stereotype.Repository;import java.util.List;/** * @author Wang * @date 2021/6/2 0012 19:52 * description */@Repositorypublic interface BookMapper {// 增加一本书 int addBook(Books books);// 删除一本书 int deleteBookById(@Param("bookID") int id);// 更新一本书 int updateBook(Books books);// 查询一本书 Books queryBookById(@Param("bookID") int id);// 查询全部的书 List queryAllBook(); Books queryBookByName(@Param("bookName") String bookName);}
mapper.xml
文件一个mapper就要有一个namespace。
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wang.dao.BookMapper">
<insert id="addBook" parameterType="Books">
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="Books">
update ssmbuild.books
set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
where bookID = #{bookID}
update>
<select id="queryBookById" resultType="Books">
select * from ssmbuild.books
where bookID = #{bookID}
select>
<select id="queryAllBook" resultType="Books">
SELECT * from ssmbuild.books
select>
<select id="queryBookByName" resultType="Books">
select * from ssmbuild.books
where bookName = '${bookName}'
select>
mapper>
service
层package com.wang.service;
import com.wang.pojo.Books;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author Wang
* @date 2021/5/12 0012 20:03
* description
*/
@Service
public interface BookService {
// 增加一本书
int addBook(Books books);
// 删除一本书
int deleteBookById(int id);
// 更新一本书
int updateBook(Books books);
// 查询一本书
Books queryBookById(int id);
// 查询全部的书
List<Books> queryAllBook();
Books queryBookByName(String bookName);
}
package com.wang.service;
import com.wang.dao.BookMapper;
import com.wang.pojo.Books;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author Wang
* @date 2021/5/12 0012 20:04
* description
*/
@Service
public class BookServiceImpl implements BookService {
// service调用dao层
@Autowired
private BookMapper bookMapper;
public int addBook(Books books) {
return bookMapper.addBook(books);
}
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
public int updateBook(Books books) {
return bookMapper.updateBook(books);
}
public Books queryBookById(int id) {
return bookMapper.queryBookById(id);
}
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
public Books queryBookByName(String bookName) {
return bookMapper.queryBookByName(bookName);
}
}
Spring-dao.xml
文件
<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">
<context:property-placeholder location="classpath:database.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<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>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.wang.dao"/>
bean>
beans>
Spring-service.xml
文件
<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" xmlns:tx="http://www.springframework.org/schema/tx"
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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.wang.service"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.wang.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
tx:attributes>
tx:advice>
beans>
右键项目名–>选择Add Frameworks Support
web.xml
<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">
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<session-config>
<session-timeout>15session-timeout>
session-config>
web-app>
Spring-mvc.xml
文件
<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">
<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>
<context:component-scan base-package="com.wang.controller" />
beans>
applicationContext.xml
文件把配置文件整合到一起即可。
<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-mvc.xml"/> <import resource="classpath:spring-service2.xml"/> <import resource="classpath:spring-dao.xml"/>beans>
BookController
类package com.wang.controller;
import com.wang.pojo.Books;
import com.wang.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
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;
/**
* @author Wang
* @date 2021/5/12 0012 21:12
* description
*/
@Controller
@RequestMapping("/book")
public class BookController {
// controller调用service层
@Autowired
private BookService bookService;
// 查询选全部的书籍,并且返回到一个书籍展示页面
@RequestMapping("/allBook")
public String list(Model model){
List<Books> list = bookService.queryAllBook();
model.addAttribute("list",list);
return "allBook";
}
// 跳转到增加书籍页面
@RequestMapping("/toAddBookPage")
public String toAddPaper(){
return "addBook";
}
// 进行添加书籍
@RequestMapping("/addBook")
public String addBook(Books books){
System.out.println("=======>"+books);
bookService.addBook(books);
return "redirect:/book/allBook";//重定向到我们的@RequestMapping("/allBook")
}
// 跳转到修改书籍页面
@RequestMapping("/toEditBookPage")
public String toEditBookPage(int id,Model model){
Books books = bookService.queryBookById(id);
model.addAttribute("books",books);
return "editBook";
}
@RequestMapping("/editBook")
public String editBook(Books books){
System.out.println("=======>"+books);
bookService.updateBook(books);
return "redirect:/book/allBook";//重定向到我们的@RequestMapping("/allBook")
}
@RequestMapping("/deleteBook/{bookId}")
public String deleteBook(@PathVariable("bookId") int id){
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
@RequestMapping("/queryBook")
public String queryBook(String queryBookName,Model model){
Books books = bookService.queryBookByName(queryBookName);
List<Books> list = new ArrayList<Books>();
list.add(books);
if(books==null){
list = bookService.queryAllBook();
model.addAttribute("error","未查到");
}
model.addAttribute("list",list);
return "allBook";
}
}
· 修改方法,可以看到WEB-INF下面只有一个classes文件,没有lib文件夹
· 把原来的这个books:war exploded
叉掉,新建一个即可
· 检查发现少了一个依赖
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.8.13version>
dependency>
Preparing: SELECT * from ssmbuild.books
Parameters:
< Columns: bookID, bookName, bookCounts, detail
< Row: 1, Java, 77, 从入门到放弃
< Row: 2, MySQL, 101, 从删库到跑路
< Row: 3, Linux, 5, 从进门到进牢哈哈哈哈
< Row: 5, 数据结构, 99, C语言版
< Row: 6, C#程序设计实用教程, 88, 机械工业出版社
< Row: 7, C程序设计, 36, 清华大学出版社
< Total: 6
// 跳转到增加书籍页面
@RequestMapping("/toAddBookPage")
public String toAddPaper(){
return "addBook";
}
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2021/6/3 0012
Time: 23:35
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>增加书籍页面title>
<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-4 column">
<div class="page-header">
<div class="alert alert-info" role="alert">
<h1>增加书籍页面h1>
div>
div>
<form action="${pageContext.request.contextPath}/book/addBook" method="post">
<div class="form-group">
<label>书籍名称label>
<input type="text" class="form-control" name="bookName" required>
div>
<div class="form-group">
<label>书籍数量label>
<input type="text" class="form-control" name="bookCounts" required>
div>
<div class="form-group">
<label>书籍描述label>
<input type="text" class="form-control" name="detail" required>
div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="添加">
div>
form>
div>
div>
div>
body>
html>
// 进行添加书籍
@RequestMapping("/addBook")
public String addBook(Books books){
System.out.println("=======>"+books);
bookService.addBook(books);
return "redirect:/book/allBook";//重定向到我们的@RequestMapping("/allBook")
}
// 跳转到修改书籍页面
@RequestMapping("/toEditBookPage")
public String toEditBookPage(int id,Model model){
Books books = bookService.queryBookById(id);
model.addAttribute("books",books);
return "editBook";
}
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2021/6/3 0012
Time: 23:35
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改书籍页面title>
<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-4 column">
<div class="page-header">
<div class="alert alert-danger" role="alert">
<h1>修改书籍页面h1>
div>
div>
<form action="${pageContext.request.contextPath}/book/editBook" method="post">
<input type="hidden" name="bookID" value="${books.bookID}">
<div class="form-group">
<label>书籍名称label>
<input type="text" class="form-control" name="bookName" value="${books.bookName}" required>
div>
<div class="form-group">
<label>书籍数量label>
<input type="text" class="form-control" name="bookCounts" value="${books.bookCounts}" required>
div>
<div class="form-group">
<label>书籍描述label>
<input type="text" class="form-control" name="detail" value="${books.detail}" required>
div>
<div class="form-group">
<input type="submit" class="btn btn-danger" value="修改">
div>
form>
div>
div>
div>
body>
html>
@RequestMapping("/editBook")
public String editBook(Books books){
System.out.println("=======>"+books);
bookService.updateBook(books);
return "redirect:/book/allBook";//重定向到我们的@RequestMapping("/allBook")
}
<input type="text" class="form-control" name="bookCounts" value="${books.bookCounts}" required>
div>
<div class="form-group">
<label>书籍描述label>
<input type="text" class="form-control" name="detail" value="${books.detail}" required>
div>
<div class="form-group">
<input type="submit" class="btn btn-danger" value="修改">
div>
form>
div>
div>
div>
body>
html>
@RequestMapping("/editBook")
public String editBook(Books books){
System.out.println("=======>"+books);
bookService.updateBook(books);
return "redirect:/book/allBook";//重定向到我们的@RequestMapping("/allBook")
}