第一次整合SSM框架笔记&代码记录,图书的增删改查,测试全部通过
文件路径
- src
- main
- java
- com.simon.controller
- BookController.java
- com.simon.dao
- BookMapper.java
- BookMapper.xml
- com.simon.entity
- Books.java
- com.simon.service
- BookService.java
- BookServiceImpl.java
- com.simon.controller
- resource
- applicationContext.xml
- db.properties
- mybatis-config.xml
- spring-dao.xml
- spring-mvc.xml
- spring-service.xml
- java
- test
- java
- Test.java
- java
- main
- web
- WEB-INF
- jsp
- addBook.jsp
- allBook.jsp
- updateBook.jsp
- web.xml
- jsp
- index.jsp
- WEB-INF
- pom.xml
- 排错思路
代码
BookController.java
package com.simon.controller;
import com.simon.entity.Books;
import com.simon.service.BookService;
import org.apache.ibatis.annotations.Param;
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.List;
@Controller
@RequestMapping("/book")
public class BookController {
//controller 调用service层
@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 toAddPage(){
return "addBook";
}
@RequestMapping("/addBooks")
public String addBook(Books books){
System.out.println("addBook->"+books);
bookService.addBook(books);
/虽然,传递数据的时候,更倾向于用转发,即return ”“;
/单数,新添加了内容到数据库,需要重新请求一次,即第二次请求
///所以需要用重定向
return "redirect: /SSM_war_exploded/book/allBook";重定向到另外一个请求
}
@RequestMapping("toUpdate")
public String toUpdatePage(int id, Model model){
Books books = bookService.queryBooksById(id);
model.addAttribute("QBook", books);
return "updateBook";
}
@RequestMapping("updateBook")
public String updateBook(Books books){
System.out.println("updateBook"+books);
bookService.updateBook(books);
return "redirect: /SSM_war_exploded/book/allBook";
}
@RequestMapping("/delete/{bookiD}")
public String deleteBook(@PathVariable("bookiD") int id){
bookService.deleteBookById(id);
return "redirect: /SSM_war_exploded/book/allBook";
}
}
BookMapper.java
package com.simon.dao;
import com.simon.entity.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookMapper {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBookById(@Param("bookId") int id);
//更新一本书
int updateBook(Books books);
//查询一本书
Books queryBooksById(@Param("bookId") int id);
//查询所有的书
List<Books> queryAllBook();
}
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.simon.dao.BookMapper">
<insert id="addBook">
insert into books(bookName, bookCounts, detail)
value (#{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>
<!--一般情况下,#{里面的参数与实体类保持一致}-->
<!--查询之外的所有方法都需要提交事务,,,,service层处理事务-->
<select id="queryBooksById" parameterType="int" resultType="books">
select * from books
where bookId = #{bookId}
</select>
<select id="queryAllBook" resultType="books">
select * from books
</select>
</mapper>
Books.java
package com.simon.entity;
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
public Books() {
}
public Books(int bookID, String bookName, int bookCounts, String detail) {
this.bookID = bookID;
this.bookName = bookName;
this.bookCounts = bookCounts;
this.detail = detail;
}
public int getBookID() {
return bookID;
}
public void setBookID(int bookID) {
this.bookID = bookID;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getBookCounts() {
return bookCounts;
}
public void setBookCounts(int bookCounts) {
this.bookCounts = bookCounts;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
@Override
public String toString() {
return "Books{" +
"bookID=" + bookID +
", bookName='" + bookName + '\'' +
", bookCounts=" + bookCounts +
", detail='" + detail + '\'' +
'}';
}
}
BookService.java
package com.simon.service;
import com.simon.entity.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookService {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBookById(int id);
//更新一本书
int updateBook(Books books);
//查询一本书
Books queryBooksById(int id);
//查询所有的书
List<Books> queryAllBook();
}
BookServiceImpl.java
package com.simon.service;
import com.simon.dao.BookMapper;
import com.simon.entity.Books;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
//业务层service调用dao层就对了
@Service
public class BookServiceImpl implements BookService{
//组合dao,即mapper
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
@Override
public int addBook(Books books) {
return bookMapper.addBook(books);
}
@Override
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
@Override
public int updateBook(Books books) {
return bookMapper.updateBook(books);
}
@Override
public Books queryBooksById(int id) {
return bookMapper.queryBooksById(id);
}
@Override
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
}
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-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:spring-mvc.xml"/>
</beans>
db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
#如果使用的是mysql8以上,还需要增加一个时区 &serverTimeZone=Asia/Shanghai ///小大大
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
jdbc.username=root
jdbc.password=root
mybatis-config.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>
<!--配置数据源,交给Spring去做-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<package name="com.simon.entity"/>
</typeAliases>
<mappers>
<!--<package name="com.simon.dao"/>-->
<mapper resource="com/simon/dao/BookMapper.xml"/>
</mappers>
</configuration>
spring-dao.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">
<!-- 配置整合mybatis -->
<!-- 1.关联数据库文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 2.数据库连接池 -->
<!--数据库连接池
hikari spring2.0默认继承x
druid
spring-jdbc
dbcp 半自动化操作 不能自动连接
c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面)
-->
<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}"/>
<!-- 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对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--============================================================================-->
<!--============================================================================-->
<!-- 4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
<!--解释 :https://www.cnblogs.com/jpfss/p/7799806.html-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="com.simon.dao"/>
</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: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/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 配置SpringMVC -->
<!-- 1.开启SpringMVC注解驱动 -->
<mvc:annotation-driven />
<!-- 2.静态资源默认servlet配置-->
<mvc:default-servlet-handler/>
<!-- 3.配置jsp 显示ViewResolver视图解析器 -->
<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>
<!-- 4.扫描web相关的bean -->
<context:component-scan base-package="com.simon.controller" />
</beans>
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"
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">
<!-- 扫描service相关的bean -->
<context:component-scan base-package="com.simon.service" />
<!--标签配置很明确,但是无法找到, context:component-scan 就是约束头没有引入-->
<!--BookServiceImpl注入到IOC容器中-->
<bean id="BookServiceImpl" class="com.simon.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!--aop支持事务-->
<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.simon.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
</beans>
Test.java
import com.simon.entity.Books;
import com.simon.service.BookService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class Test {
@org.junit.Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
BookService userService = (BookService) context.getBean("BookServiceImpl");
List<Books> books = userService.queryAllBook();
for (Books book : books) {
System.out.println(book);
}
}
}
addBook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>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-12 column">
<div class="page-header">
<h1>
<small>新增书籍</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/addBooks" method="post" >
<div class="form-group">
<label>书籍名称</label>
<input type="text" name="bookName" class="form-control" placeholder="请输入输入书籍名称" required>
</div>
<div class="form-group">
<label>书籍数量</label>
<input type="text" name="bookCounts" class="form-control" placeholder="请输入输入书籍名称" required>
</div>
<div class="form-group">
<label>书籍详情</label>
<input type="text" name="detail" class="form-control" placeholder="去哦那个输入书籍名称" required>
</div>
<div class="form-group">
<input type="submit" class="form-control" value="提交">
</div>
</form>
</div>
</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>
</head>
<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<body>
<h1>书籍展示</h1>
<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>
</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>
<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/toUpdate?id=${book.bookID}">修改</a>
|
<a href="${pageContext.request.contextPath}/book/delete/${book.bookID}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
updateBook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>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-12 column">
<div class="page-header">
<h1>
<small>修改书籍</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/updateBook" method="post" >
<%--出现的问题:
提交了修改的SQL请求但是修改失败,初次思考,是事务问题,配置事务完毕依旧失败
查看sql语句,是根据id去修改的,sql执行失败,修改未完成--%>
<%--前端传递隐藏域名--%>
<div class="form-group">
<input type="hidden" name="bookID" value="${QBook.bookID}" class="form-control">
</div>
<div class="form-group">
<label>书籍名称</label>
<input type="text" name="bookName" class="form-control" value="${QBook.bookName}" required>
</div>
<div class="form-group">
<label>书籍数量</label>
<input type="text" name="bookCounts" class="form-control" value="${QBook.bookCounts}" required>
</div>
<div class="form-group">
<label>书籍详情</label>
<input type="text" name="detail" class="form-control" value="${QBook.detail}" required>
</div>
<div class="form-group">
<input type="submit" class="form-control" value="修改">
</div>
</form>
</div>
</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>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>
<!--encodingFilter-->
<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>15</session-timeout>
</session-config>
</web-app>
index.jsp
<%--
Created by IntelliJ IDEA.
User: KZSIMON
Date: 2021/7/25
Time: 10:49
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<style>
a{
text-decoration: none;
color: black;
font-size: 38px;
}
h3{
width: 180px;
height: 38px;
margin: 100px auto;
text-align: center;
/*行高跟字体一样,就剧中了*/
line-height: 38px;
background: deepskyblue;
}
</style>
<body>
$END$
<h1>ClassNotFound---导包</h1>
<h1>spring-dao.xml没有找到,用提示的方式,重新检查一个总的文件和独自的文件</h1>
<h1>class="form-inline"</h1>
<h1>写业务,从下往上写,</h1>
<h1>先写dao层,接口,然后*Mapper.xml。然后,service层,接口,实现类。最后Controller层</h1>
<h1>验证业务,从上往下,从前端,到controller,service,dao</h1>
<a href="${pageContext.request.contextPath}/book/allBook"><h3>进入书籍</h3></a>
</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.simon</groupId>
<artifactId>SSM</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<!--依赖问题,junit,数据库驱动,连接池,servlet,jsp,mybatis,mybatis-spring,spring-->
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</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.0</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>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</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>
排错思路
问题:bean不存在
步骤:
- 查看这个bean是否诸如成功,即点击前面的spring标志,能否自动跳转
- Junit测试单元,看看代码是否能够查询出来结果
- 问题不在底层,是spring出了问题
- SpringMVC,整合的时候没有调用到我们的service层的bean
1.applicationContext.xml没有注入bean
2.web.xml中我们也绑定郭配置文件//发现问题,配置的是spring-mvc.xml,里面确实没有service