整合SSM框架
最近把SSM框架的视频快速的过了一遍,虽然啥都没学会,但还是想在最后整合SSM框架的时候玩儿一下
一、环境要求
- IDEA
- MySQL 5.7.X
- Tomcat 9
- Maven 3.6
二、数据库环境搭建
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,'从进门到进牢');
三、基本环境搭建
-
创建一个Maven项目,名称为ssmbuild,并且添加web支持!
-
导入相关的pom依赖
<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.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.9.RELEASE</version> </dependency> <!--lombok,方便实体类的构造get/set等--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.28</version> </dependency> </dependencies>
-
在pom文件中添加资源过滤设置
<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>
-
建立基本的项目结构
-
com.lovedfl.pojo
-
com.lovedfl.dao
-
com.lovedfl.service
-
com.lovedfl.controller
-
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> </configuration>
-
applicationConfig.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"> </beans>
基本项目结构截图:
小tips:这里我们可以直接在项目中新建一个node.md文件,将mybatis和spring的核心配置文件的基本框架放在文件中,后面需要用的时候就可以直接复制了
-
思、MyBatis层编写
-
数据库配置文件,database.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=false&useUnicode=true&characterEncoding=utf8 jdbc.username=root jdbc.password=root
-
编写MyBatis核心配置文件,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> <!--可以为实体类起别名 利用包扫描机制,该包下面的所有实体类都会被起别名 --> <typeAliases> <package name="com.lovedfl.pojo"/> </typeAliases> <!--绑定注册我们的mapper文件--> <mappers> <package name="com.lovedfl.dao"/> </mappers> </configuration>
-
编写数据中对应的实体类
利用lombok方便开发
package com.lovedfl.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data // 提供get/set,toString等方法 @AllArgsConstructor // 全参构造 @NoArgsConstructor // 无参构造 public class Books { private int bookID; private String bookName; private String bookCounts; private String detail; }
-
编写Dao层的接口
package com.lovedfl.dao; import com.lovedfl.pojo.Books; import java.util.List; public interface BooksMapper { // 增加一本图书 int addBook(Books books); // 根据id删除一本图书 int deleteBookById(int id); // 更新一本图书 int updateBook(Books books); // 根据id查询图书 Books queryBookById(int id); // 查询所有图书 List<Books> queryAllBook(); }
-
编写Dao层对应接口的mapper.xml文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper> <!--增加一本图书--> <insert id="addBook" parameterType="books"> insert into books(bookName,bookCounts,detail) values (#{bookName},#{bookCounts},#{detail}) </insert> <!--根据id删除一本图书--> <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; </update> <!--根据id查询图书--> <select id="queryBookById" resultType="books" parameterType="_int"> select * from books where bookID = #{bookID} </select> <!--查询所有图书--> <select id="queryAllBook" resultType="books"> select * from books </select> </mapper>
-
编写service层的接口和实现类
接口:
package com.lovedfl.service; import com.lovedfl.pojo.Books; import java.util.List; public interface BooksService { // 增加一本图书 int addBook(Books books); // 根据id删除一本图书 int deleteBookById(int id); // 更新一本图书 int updateBook(Books books); // 根据id查询图书 Books queryBookById(int id); // 查询所有图书 List<Books> queryAllBook(); }
实现类:
package com.lovedfl.service; import com.lovedfl.dao.BooksMapper; import com.lovedfl.pojo.Books; import java.util.List; public class BooksServiceImpl implements BooksService{ //调用dao层的操作,设置一个set接口,方便Spring管理 private BooksMapper booksMapper; public void setBooksMapper(BooksMapper booksMapper) { this.booksMapper = booksMapper; } @Override public int addBook(Books books) { return booksMapper.addBook(books); } @Override public int deleteBookById(int id) { return booksMapper.deleteBookById(id); } @Override public int updateBook(Books books) { return booksMapper.updateBook(books); } @Override public Books queryBookById(int id) { return booksMapper.queryBookById(id); } @Override public List<Books> queryAllBook() { return booksMapper.queryAllBook(); } }
五、Spring层编写
-
配置Spring整合MyBatis,这里数据源我们使用c3p0
-
编写Spring整合MyBatis的配置文件,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 http://www.springframework.org/schema/context/spring-context.xsd"> <!--整合MyBatis配置文件--> <!--1、关联配置文件--> <context:property-placeholder location="classpath:database.properties"/> <!--2、数据库连接池--> <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"/> <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.lovedfl.dao"/> </bean> </beans>
-
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" 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"> <!-- 扫描service相关的bean --> <context:component-scan base-package="com.lovedfl.service"/> <!--BookServiceImpl注入到IOC容器中--> <bean id="booksServiceImpl" class="com.lovedfl.service.BooksServiceImpl"> <property name="booksMapper" ref="booksMapper"/> </bean> <!-- 配置事务管理器 --> <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="dataSource"/> </bean> </beans>
六、SpringMVC编写
-
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>
-
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"> <!-- 配置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.lovedfl.controller"/> </beans>
-
spring配置整合文件,applicationCointext.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>
配置文件编写结束!下面开始Controller和视图层的编写
-
BookController类编写,方法一:查询全部书籍
@Controller @RequestMapping("/book") public class BookController { @Autowired @Qualifier("booksServiceImpl") private BooksService booksService; @RequestMapping("/allBook") public String list(Model model) { List<Books> list = booksService.queryAllBook(); model.addAttribute("list", list); return "allBook"; } }
-
编写首页index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE HTML> <html> <head> <title>首页</title> <style type="text/css"> 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/allBook">点击进入列表页</a> </h3> </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> <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> </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>
-
BookController类编写,方法二:添加书籍
@RequestMapping("/toAddBook") public String toAddPaper() { return "addBook"; } @RequestMapping("/addBook") public String addPaper(Books books) { booksService.addBook(books); return "redirect:/book/allBook"; }
-
添加书籍页面:addBook.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> <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> <form action="${pageContext.request.contextPath}/book/addBook" method="post"> 书籍名称:<input type="text" name="bookName"><br><br><br> 书籍数量:<input type="text" name="bookCounts"><br><br><br> 书籍详情:<input type="text" name="detail"><br><br><br> <input type="submit" value="添加"> </form> </div>
-
BookController类编写,方法三:修改书籍
@RequestMapping("/toUpdateBook") public String toUpdateBook(Model model, int id) { Books books = booksService.queryBookById(id); System.out.println(books); model.addAttribute("book",books ); return "updateBook"; } @RequestMapping("/updateBook") public String updateBook(Model model, Books book) { System.out.println(book); booksService.updateBook(book); Books books = booksService.queryBookById(book.getBookID()); model.addAttribute("books", books); return "redirect:/book/allBook"; }
-
修改书籍页面:updateBook.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> <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> <form action="${pageContext.request.contextPath}/book/updateBook" method="post"> <input type="hidden" name="bookID" value="${book.getBookID()}"/> 书籍名称:<input type="text" name="bookName" value="${book.getBookName()}"/> 书籍数量:<input type="text" name="bookCounts" value="${book.getBookCounts()}"/> 书籍详情:<input type="text" name="detail" value="${book.getDetail() }"/> <input type="submit" value="提交"/> </form> </div>
-
BookController类编写,方法四:删除书籍
@RequestMapping("/del/{bookId}") public String deleteBook(@PathVariable("bookId") int id) { booksService.deleteBookById(id); return "redirect:/book/allBook"; }
到此SSM整合的小案例就结束了。
项目完整结构:
标签:框架,int,书籍,id,SSM,books,整合,Books,public From: https://www.cnblogs.com/lovedfl/p/17542526.html