6.ssm项目整合源码
项目结构
时刻记住maven的导入资源问题
配置过程:projectStructure->Artifacys->lib->+
1.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"> <parent> <artifactId>springMVC-study</artifactId> <groupId>org.example</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>ssm</artifactId> <dependencies> <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.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.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.19.RELEASE</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.10</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.13</version> </dependency> </dependencies> <!--静态资源导出问题--> <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build> </project>
2.建立一个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>
3.配置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> <!--1.使用标准的日志--> <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <!--2.配置数据源,交给spring去做,起别名操作,默认是实现类名字第一个小写--> <typeAliases> <package name="com.wu.pojo"/> </typeAliases> <!--3.注册接口--> <mappers> <mapper class="com.wu.dao.BookMapper"/> </mappers> </configuration>
4.编写pojo,dao层的接口和xml文件
Books
import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @author wuyimin * @create 2021-06-12-11:42 * @description */ @Data @AllArgsConstructor @NoArgsConstructor public class Books { private int bookID; private String bookName; private String bookCounts; private String detail; }
BookMapper.java
package com.wu.dao; import com.wu.pojo.Books; import org.apache.ibatis.annotations.Param; import java.util.List; /** * @author wuyimin * @create 2021-06-12-11:46 * @description */ public interface BookMapper { //增加一本书 int addBook(Books books); //删除一本书 int deleteBookById(@Param("bookId") int id); //更新一本书 int updateBookById(Books books); //根据id查询一本书 Books queryBookById(@Param("bookId")int id); //查询全部的书 List<Books> queryAllBook(); //查询书通过书名 Books queryBookByName(@Param("bookName") String name); }
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.wu.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="updateBookById" 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>
5.准备一个database.properties去保存连接的信息
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf-8 jdbc.username=root jdbc.password=root
6.配置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"> <!--1.关联数据库配置文件--> <context:property-placeholder location="classpath:database.properties"/> <!--2.连接池 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}"/> <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"/> <!--绑定mybatis的配置文件--> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean> <!-- 4.配置dao接口扫描包,动态实现列dao接口可以注入到spring容器--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 注入sqlSessionFactory--> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!--扫描dao接口--> <property name="basePackage" value="com.wu.dao"/> </bean> </beans>
7.编写service层的接口和实现类
BookService:
package com.wu.service; import com.wu.pojo.Books; import java.util.List; /** * @author wuyimin * @create 2021-06-12-12:08 * @description */ public interface BookService { //增加一本书 int addBook(Books books); //删除一本书 int deleteBookById(int id); //更新一本书 int updateBookById(Books books); //根据id查询一本书 Books queryBookById(int id); //查询全部的书 List<Books> queryAllBook(); Books queryBookByName(String name); }
BookServiceImpl:这里使用的是配置文件注入不是注解注入(我的理解是在一个类里使用其他类的对象的时候就需要注入)
package com.wu.service; import com.wu.dao.BookMapper; import com.wu.pojo.Books; import java.util.List; /** * @author wuyimin * @create 2021-06-12-12:09 * @description */ public class BookServiceImpl implements BookService { //在实现类里组合dao private BookMapper bookMapper; public void setBookMapper(BookMapper bookMapper) { this.bookMapper = bookMapper; } public int addBook(Books books) { return bookMapper.addBook(books); } public int deleteBookById(int id) { return bookMapper.deleteBookById(id); } public int updateBookById(Books books) { return bookMapper.updateBookById(books); } public Books queryBookById(int id) { return bookMapper.queryBookById(id); } public List<Books> queryAllBook() { return bookMapper.queryAllBook(); } public Books queryBookByName(String name) { return bookMapper.queryBookByName(name); } }
9.编写spring-service的配置文件
<?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"> <!--1.扫描service下的包--> <context:component-scan base-package="com.wu.service"/> <!--2.将我们所有业务类注入到spring,可以通过配置或者注解实现(实现类上面使用@Service注解,在bookmapper属性上使用@Autowired)--> <bean id="BookServiceImpl" class="com.wu.service.BookServiceImpl"> <property name="bookMapper" ref="bookMapper"/> </bean> <!--3.声明式事务配置--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--注入数据源--> <property name="dataSource" ref="dataSource"/> </bean> <!-- 4.aop事务支持(后续可能导入)从Spring的角度看,AOP最大的用途就在于提供了事务管理的能力。事务管理就是一个关注点,你的正事就是去访问数据库,而你不想管事务(太烦),
所以,Spring在你访问数据库之前,自动帮你开启事务,当你访问数据库结束之后,自动帮你提交/回滚事务!--> <!-- 配置事务通知--> <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.wu.service.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/> </aop:config> </beans>
10.添加web框架,编写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"> <!--1.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> <!-- 2.乱码过滤--> <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> <!-- 3.Session 15分钟后超时--> <session-config> <session-timeout>15</session-timeout> </session-config> </web-app>
11.编写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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 1.注解驱动--> <mvc:annotation-driven/> <!-- 2.静态资源过滤--> <mvc:default-servlet-handler/> <!-- 3.扫描包--> <context:component-scan base-package="com.wu.controller"/> <!-- 4.视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
12.编写controller层代码
BookController:
package com.wu.controller; import com.wu.pojo.Books; import com.wu.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; /** * @author wuyimin * @create 2021-06-12-13:11 * @description */ @Controller @RequestMapping("/book") public class BookController { @Autowired//使用变量方式注入 @Qualifier("BookServiceImpl")//表明了哪个实现类才是我们所需要的 private BookService bookService; //查询全部的书籍,并且返回到一个书籍的展示页面 @RequestMapping("/allBook") public String list(Model model){ List<Books> bookList=bookService.queryAllBook(); model.addAttribute("list",bookList); return "allBook"; } //跳转到增加书籍的页面 @RequestMapping("/toAddBook") public String toAddPaper (Model model){ return "addBook"; } //添加书籍的请求 @RequestMapping("/addBook") public String addBook(Books books){ bookService.addBook(books); return "redirect:/book/allBook";//重定向到我们的/allBook请求 } @RequestMapping("/toUpdateBook") //跳转到修改的页面 public String toUpdatePaper(int id,Model model){ Books books = bookService.queryBookById(id); model.addAttribute("QBook",books); return "updateBook"; } @RequestMapping("/updateBook") public String updateBook(Books books){ bookService.updateBookById(books); return "redirect:/book/allBook"; } // 使用restful风格 @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"; } }
13.jsp文件
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <%--相对路径,防止项目转移后不能使用--%> <a href="${pageContext.request.contextPath}/book/allBook">点击此处进入书城</a> </body> </html>
addBook.jsp
<%@ 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"> <%--等分屏幕为12份--%> <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>书籍名称</label> <input type="text" name="bookName" class="form-control" required> </div> <div class="form-group"> <label>书籍数量</label> <input type="text" name="bookCounts" class="form-control" required> </div> <div class="form-group"> <label>书籍描述</label> <input type="text" name="detail" class="form-control" required> </div> <div class="form-group"> <input type="submit" class="form-control" value="添加"> </div> </form> </div> </body> </html>
allBook
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ 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: 5px;--%> <%-- }--%> <%-- </style>--%> <%--使用外部--%> <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"> <%--等分屏幕为12份--%> <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-4 column"></div> <div class="col-md-4 column"> <form action="${pageContext.request.contextPath}/book/queryBook" method="post" style="float:right"> <span style="color: red;font-weight: bold">${error}</span> <input type="text" name="queryBookName" class="from-control" placeholder="请输入要查询的书籍名称"> <input type="submit" value="查询" class="btn btn-primary"> </form> </div> </div> </div> <div class="row clearfix"> <%--等分屏幕为12份--%> <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> <%--从list中遍历出来--%> </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?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>
updateBook
<%@ 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"> <%--等分屏幕为12份--%> <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"> <%-- 需要一个id的传入--%> <input type="hidden" name="bookID" value="${QBook.bookID}"> <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>