SSM完整笔记
官网文档
CREATE DATABASE `ssmbuild`;
USE `ssmbuild`;
DROP TABLE IF EXISTS `books`;
CREATE TABLE `books` (
`bookID` int(11) NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '书名',
`bookCounts` int(11) NOT NULL COMMENT '数量',
`detail` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '描述',
INDEX `bookID`(`bookID`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8;
INSERT INTO `books` VALUES (1, 'Java', 11, '从入门到放弃');
INSERT INTO `books` VALUES (2, 'MySQL', 10, '从删库到跑路');
INSERT INTO `books` VALUES (3, 'Linux', 5, '从进门到进牢');
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.3.8version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.46version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.20version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>4.0.1version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.2.1-b03version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>com.mchangegroupId>
<artifactId>c3p0artifactId>
<version>0.9.5.5version>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.9.7version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.6version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.3.8version>
dependency>
dependencies>
<build>
<resources>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>truefiltering>
resource>
resources>
build>
jdbc.driver=com.mysql.jdbc.Driver
# 如果使用的是Mysql8.0以上,就得加上时区设置
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
jdbc.username=chelsea
jdbc.password=********
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="LOG4J"/>
settings>
<typeAliases>
<package name="com.chelsea.pojo"/>
typeAliases>
<mappers>
<mapper resource="com/chelsea/mapper/BookMapper.xml"/>
mappers>
configuration>
public interface BookMapper {
/*增加一本书*/
int addBook(Books books);
/*删除一本书*/
int deleteBookById(@Param("bookID") int bookID);
/*修改一本书*/
int updateBook(Books books);
/*查询一本书*/
Books queryBookById(@Param("bookID") int id);
/*查询所有书*/
List<Books> queryAllBook();
/*查询书籍*/
List<Books> queryBooks(@Param("queryInfo") String queryInfo);
}
<mapper namespace="com.chelsea.mapper.BookMapper">
<insert id="addBook" parameterType="Books">
insert into books (bookName,bookCounts,detail) values (#{bookName},#{bookCounts},#{detail})
insert>
<delete id="deleteBookById" parameterType="_int">
delete from books where bookID = #{bookID}
delete>
<update id="updateBook" parameterType="Books">
update books set bookName = #{bookName},bookCounts=#{bookCounts},detail=#{detail} where bookID = #{bookID}
update>
<select id="queryBookById" parameterType="_int" resultType="Books">
select * from books where bookID = #{bookID}
select>
<select id="queryAllBook" resultType="Books">
select * from books
select>
<select id="queryBooks" resultType="Books" parameterType="String">
select * from books where bookName like "%"#{queryInfo}"%"
select>
mapper>
public class BookServiceImpl implements BookService {
/*service层要调用mapper层,所以要组合进来*/
private BookMapper bookMapper;
//set方法为了自动注入
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
@Override
public int addBook(Books books) {
return bookMapper.addBook(books);
}
@Override
public int deleteBookById(int bookID) {
return bookMapper.deleteBookById(bookID);
}
@Override
public int updateBook(Books books) {
return bookMapper.updateBook(books);
}
@Override
public Books queryBookById(int id) {
return bookMapper.queryBookById(id);
}
@Override
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
@Override
public List<Books> queryBooks(String queryInfo) {
return bookMapper.queryBooks(queryInfo);
}
}
<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
https://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:db.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.chelsea.mapper"/>
bean>
beans>
<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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.chelsea.service"/>
<bean id="BookServiceImpl" class="com.chelsea.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.chelsea.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
aop:config>
beans>
<servlet>
<servlet-name>dispatcherServletservlet-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>dispatcherServletservlet-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>
<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
https://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/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
<mvc:annotation-driven/>
<context:component-scan base-package="com.chelsea.controller"/>
<mvc:default-servlet-handler/>
beans>
<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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:spring-mapper.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:spring-mvc.xml"/>
beans>
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
/*查询全部书籍并且返回到展示页面*/
@RequestMapping("/allBook")
public String list(Model model){
List<Books> booksList = bookService.queryAllBook();
model.addAttribute("bookList",booksList);
return "allBook";
}
/*跳转到增加书籍页面*/
@RequestMapping("/toAddBook")
public String toAddBook(){
return "addBook";
}
/*添加书籍的请求*/
@RequestMapping(value = "/addBook",method = RequestMethod.GET)
public String addBook(Books books){
System.out.println(books);
bookService.addBook(books);
/*重定向到allBook*/
return "redirect:/book/allBook";
}
/*跳转到修改页面*/
@RequestMapping("/toUpdate")
public String toUpdate(@Param("id") int id, Model model){
System.out.println("update id is : "+id);
Books books = bookService.queryBookById(id);
model.addAttribute("books",books);
return "updateBook";
}
/*修改数据*/
@RequestMapping("/updateBook")
public String updateBook(Books books){
System.out.println("修改书籍:"+books);
bookService.updateBook(books);
return "redirect:/book/allBook";
}
/*删除数据*/
@RequestMapping("/deleteBook/{bookID}")
public String deleteBook(@PathVariable("bookID") int id){
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
/*查询书籍,使用like语句进行模糊查询,如果为空则会返回所有数据*/
@RequestMapping("/queryBook")
public String queryBook(String queryInfo,Model model){
/*如果为空会默认显示全部数据*/
List<Books> queryList = bookService.queryBooks(queryInfo);
//未查到信息:这种情况不存在
if(queryList.size()==0){
queryList = bookService.queryAllBook();
model.addAttribute("error","未查到书籍信息");
}
model.addAttribute("bookList",queryList);
return "allBook";
}
}
<html>
<head>
<title>Titletitle>
<%--使用bootstrap CDN--%>
<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 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-8 column">
<%--查询书籍--%>
<form class="form-inline" action="${pageContext.request.contextPath}/book/queryBook" method="get" style="float: right">
<span style="color: red;font-weight: bold">${error}span>
<input type="text" placeholder="查询书籍" class="form-control" name="queryInfo">
<input type="submit" value="查询" class="btn btn-primary">
form>
div>
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>
<%--从list中遍历数据--%>
<tbody>
<c:forEach var="book" items="${bookList}">
<tr>
<td>${book.bookID}td>
<td>${book.bookName}td>
<td>${book.bookCounts}td>
<td>${book.detail}td>
<td>
<a href="${pageContext.request.contextPath}/book/toUpdate?id=${book.bookID}">修改a>
|
<a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}">删除a>
td>
tr>
c:forEach>
tbody>
table>
div>
div>
div>
body>
html>