【Spring + SpringMVC + Mybatis】 SSM 整合
环境搭建要求:
软件环境:
- Windows7 x64 +
- IDEA 2018 +
- MySQL 5.0 +
- Tomcat 8 +
- Maven 3.0 +
【建议:越新越好】
知识点:
- MySQL数据库操作
- Spring
- JavaWeb
- Mybatis
- 前端基础
设计过程:
分析需求 - 设计数据库 - 业务 - 前端界面
创建演示库:
CREATE DATABASE IF NOT EXISTS `ssm`;
创建演示的用户表
USE `ssm`; CREATE TABLE `user`( `user_id` INT PRIMARY KEY AUTO_INCREMENT, `user_name` VARCHAR(10), `user_password` VARCHAR(20));
插入演示数据
INSERT INTO `user` VALUES (1,‘USER01‘,‘111111‘), (2,‘USER02‘,‘222222‘), (3,‘USER03‘,‘333333‘);
打开IDEA创建SSM整合工程
配置POM.xml依赖
【测试完之后放上来的,所有依赖都在这里了】
<dependencies> <!-- Junit --> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> <scope>test</scope> </dependency> <!-- Jdbc --> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.20</version> </dependency> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.6.6</version> </dependency> <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- - - - - - - - - - - - - 4种连接池 - - - - - - - - - - - - - - - - - --> <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.5</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.7.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.8.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.22</version> </dependency> <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>3.4.2</version> </dependency> <!-- - - - - - - - - - - - - SSM - - - - - - - - - - - - - - - --> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.6.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.6.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.4</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.4</version> </dependency> <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.5</version> </dependency> <!-- - - - - - - - - - - - -Servlet- - - - - - - - - - - - - - - - --> <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl --> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.taglibs/taglibs-standard-spec --> <dependency> <groupId>org.apache.taglibs</groupId> <artifactId>taglibs-standard-spec</artifactId> <version>1.2.5</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.taglibs/taglibs-standard-impl --> <dependency> <groupId>org.apache.taglibs</groupId> <artifactId>taglibs-standard-impl</artifactId> <version>1.2.5</version> </dependency> </dependencies>
考虑资源导出过滤问题
【一般配置文件不放在包里面就不需要写】
<!--在build中配置resources,来防止我们资源导出失败的问题--> <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>
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> </configuration>
Application-Context.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:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd " > </beans>
Jdbc.properties
jdbc.driver = com.mysql.cj.jdbc.Driver jdbc.url = jdbc:mysql:///ssm?serverTimezone=Asia/Shanghai jdbc.username = root jdbc.password = 123456 # The url may some poor,you can use this params # useSSL=true # useUnicode=true # characterEncoding=utf-8 # serverTimezone=GMT # The MySQL8.0+ Must add serverTimezone param # And driver is : com.mysql.cj.jdbc.Driver # In MySQL5.0+ # The driver is : com.mysql.jdbc.Driver
Mybatis类型别名处理
<typeAliases> <package name="cn.dai.pojo"/> </typeAliases>
用户表的BeanClass编写
package cn.dai.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @author ArkD42 * @file SSM Integration * @create 2020 - 05 - 07 - 22:43 */ @Data @AllArgsConstructor @NoArgsConstructor public class User { private Integer user_id; private String user_name; private String user_password; }
Dao接口【Mapper接口】
可以不写映射器,但是最好写一个测试用
public interface UserMapper { @Select("SELECT * FROM `user`;") List<User> getAllUser(); @Select("SELECT * FROM `user` WHERE `user_id` = #{USER_ID};") User getUserById(@Param("USER_ID") Integer id); @Insert("INSERT " + "INTO `user`(user_name,user_password) " + "VALUES(#{user_name},#{user_password});") int addUser(User user); @Update("UPDATE `user` " + "SET user_name = #{user_name},user_password = #{user_password} " + "WHERE user_id = #{user_id};") int updateUserById(User user); @Delete("DELETE FROM `user` WHERE user_id = #{user_id};") int deleteUserById(@Param("USER_ID") Integer id); }
UserMapper.xml
放在resources.mappers下面
你也可以放接口的包里一起,就是要注意资源导出【要补上那个pom.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 namespace="cn.dai.mapper.UserMapper"> </mapper>
注册映射器给Mybatis-Config.xml
<mappers> <mapper resource="mappers/UserMappers.xml"/> </mappers>
配置LOG4J日志记录
Mybatis-Config.xml设置日志输出
【自己注意下约束的顺序要求】
<settings> <setting name="logImpl" value="LOG4J"/> </settings>
Log4J.properties
#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码 log4j.rootLogger=DEBUG,console,file # Settings About ConsoleOutput log4j.appender.console = org.apache.log4j.ConsoleAppender log4j.appender.console.Target = System.out log4j.appender.console.Threshold=DEBUG log4j.appender.console.layout = org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=[%c]-%m%n # Settings About FileOutput log4j.appender.file = org.apache.log4j.RollingFileAppender log4j.appender.file.File=./resources/log/logging.log log4j.appender.file.MaxFileSize=10mb log4j.appender.file.Threshold=DEBUG log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n # LogOutput Level log4j.logger.org.mybatis=DEBUG log4j.logger.java.sql=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.ResultSet=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
配置文件的命名和存放位置
因为是和SLF4J的API一起用的
所以还要再加一个 SLF4J + LOG4J 的依赖
<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.6.6</version> </dependency>
在要输出记录的类中设置日志实例
private static Logger logger = Logger.getLogger(Sample.class);
数据源【连接池】配置移交给Spring配置
Spring层的配置
连接参数、连接池、SQL会话工厂的配置
<!-- 使用Spring加载JDBC连接参数 --> <context:property-placeholder location="classpath:ConnectParam.properties" /> <!-- hikari连接池的配置 --> <bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig"> <property name="dataSourceProperties"> <props> <prop key="url">${jdbc.url}</prop> <prop key="user">${jdbc.username}</prop> <prop key="password">${jdbc.password}</prop> </props> </property> </bean> <!-- 连接池 c3p0 dbcp hikari druid --> <bean name="dataSource" class="com.zaxxer.hikari.HikariDataSource"> <constructor-arg name="configuration" ref="hikariConfig" /> </bean> <!--<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}"/> <!– 还可以设置其他功能–> </bean>--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 绑定连接池 --> <property name="dataSource" ref="dataSource" /> <!-- 绑定Mybatis-Config.xml--> </bean>
实现UserMapper继承DaoSupport
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper { public List<User> getAllUser() { return getSqlSession().getMapper(UserMapper.class).getAllUser(); } public User getUserById(Integer id) { return getSqlSession().getMapper(UserMapper.class).getUserById(id); } public int addUser(User user) { return getSqlSession().getMapper(UserMapper.class).addUser(user); } public int updateUserById(User user) { return getSqlSession().getMapper(UserMapper.class).updateUserById(user); } public int deleteUserById(Integer id) { return getSqlSession().getMapper(UserMapper.class).deleteUserById(id); } }
到Spring容器中注册
<!-- 配置DAO接口扫描包 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 会话工厂实例注入 --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> <!-- 接口包的位置 --> <property name="basePackage" value="cn.dai.mapper"/> </bean>
业务层的编写:
用户业务接口:
package cn.dai.service; import cn.dai.pojo.User; import java.util.List; /** * @author ArkD42 * @file SSM Integration * @create 2020 - 05 - 08 - 0:06 */ public interface UserService { List<User> queryAll(); User queryOneById(Integer id); int addUser(User user); int changeUser(User user); int removeUserById(Integer id); }
实现类
package cn.dai.service; import cn.dai.mapper.UserMapper; import cn.dai.pojo.User; import java.util.List; /** * @author ArkD42 * @file SSM Integration * @create 2020 - 05 - 08 - 0:09 */ public class UserServiceImpl implements UserService{ private UserMapper userMapper; public void setUserMapper(UserMapper userMapper) { this.userMapper = userMapper; } public UserServiceImpl(UserMapper userMapper) { this.userMapper = userMapper; } public List<User> queryAll() { return userMapper.getAllUser(); } public User queryOneById(Integer id) { return userMapper.getUserById(id); } public int addUser(User user) { return userMapper.addUser(user); } public int changeUser(User user) { return userMapper.updateUserById(user); } public int removeUserById(Integer id) { return userMapper.deleteUserById(id); } }
以xml方式注册
<!-- 开启注解扫描 --> <context:component-scan base-package="cn.dai.service"/> <!-- 手动配置 --> <!--<bean id="userService" class="cn.dai.service.UserServiceImpl"> <property name="userMapper" ref="userMapper"/> </bean>-->
或者注解:
事务的配置:
<!-- 声明式事务配置--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 数据源的导入 --> <property name="dataSource" ref="dataSource" /> </bean>
测试调试程序:
连接池测试【数据源配置问题】
在前面的Hikari连接池配置中,很有可能配置错!!!
这里使用原生硬编码写一遍链接测试,再把容器配置对照着修改
import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import org.apache.log4j.Logger; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; /** * @author ArkD42 * @file SSM Integration * @create 2020 - 05 - 08 - 0:28 */ public class HikariTest { private static Logger logger = Logger.getLogger(HikariTest.class); @Test public void connectTest() throws SQLException { HikariConfig hikariConfig = new HikariConfig(); hikariConfig.setJdbcUrl("jdbc:mysql:///ssm?serverTimezone=Asia/Shanghai"); hikariConfig.setUsername("root"); hikariConfig.setPassword("123456"); HikariDataSource dataSource = new HikariDataSource(hikariConfig); Connection connection = dataSource.getConnection(); System.out.println(connection); } }
然后测试容器实例
容器实例&业务层的调用 是否正常
import cn.dai.pojo.User; import cn.dai.service.UserService; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.List; /** * @author ArkD42 * @file SSM Integration * @create 2020 - 05 - 08 - 0:23 */ public class ServiceTest { @Test public void serviceTest(){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("SpringContexts\\Bean-Context.xml"); System.out.println(applicationContext); } @Test public void serviceTest2(){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("SpringContexts\\Bean-Context.xml"); UserService userService = applicationContext.getBean("userServiceImpl", UserService.class); List<User> users = userService.queryAll(); for (User user: users) { System.out.println(user); } } }
SpringMVC层的配置
添加Web框架
配置【转发中心】&【乱码过滤器】
【web.xml】
注意:转发中心加载的应该是所有导入的总容器
<!-- MVC转发中心 --> <servlet> <servlet-name>MVC DispatcherCenter</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:SpringContexts/Mvc-Context.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>MVC DispatcherCenter</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- MVC乱码过滤器--> <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>
配置转发中心初始化加载的Spring容器
【Mvc-Context.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:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd " > </beans>
回到Bean容器导入Mvc容器
<import resource="classpath:SpringContexts/Dao-Context.xml"/> <import resource="classpath:SpringContexts/Service-Context.xml"/> <import resource="classpath:SpringContexts/Mvc-Context.xml"/>
配置MVC的相关
【Mvc-Context.xml】
<!-- 注解驱动 --> <mvc:annotation-driven /> <!-- 静态资源过滤 --> <mvc:default-servlet-handler/> <!-- 控制器扫描位置 --> <context:component-scan base-package="cn.dai.controller" /> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean>
测试:
编写用户控制器
注意业务层的获取,Bean的注册是否正常
package cn.dai.controller; import cn.dai.pojo.User; import cn.dai.service.UserService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.annotation.Resource; import java.util.List; /** * @author ArkD42 * @file SSM Integration * @create 2020 - 05 - 08 - 7:37 */ @Controller @RequestMapping("/User") public class UserController { //@Autowired @Qualifier("userServiceImpl") @Resource private UserService userService; @RequestMapping("/allUser") public String userList(Model model){ List<User> allUser = userService.queryAll(); model.addAttribute("allUser",allUser); return "userList"; } }
用户列表JSP
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%-- Created by IntelliJ IDEA. User: Administrator Date: 2020/5/8 Time: 7:43 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>所有用户信息</title> </head> <body> <h2>用户列表</h2> <table border="1"> <thead> <tr> <th>用户ID</th> <th>用户名称</th> <th>用户密码</th> </tr> </thead> <tbody> <c:forEach var="user" items="${allUser}"> <tr> <td>${user.user_id}</td> <td>${user.user_name}</td> <td>${user.user_password}</td> </tr> </c:forEach> </tbody> </table> </body> </html>
首页配置
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>SSM Integration</title> </head> <body> <p><a href="${pageContext.request.contextPath}/User/allUser">[查看所有用户]</a></p> </body> </html>
Tomcat配置
不要忘记导入依赖给Web,否则就要报Bean初始化异常了
开始访问
又报找不到类异常,演示的库没有JSTL
导入、重建、再导入Web
<!-- https://mvnrepository.com/artifact/org.apache.taglibs/taglibs-standard-spec --> <dependency> <groupId>org.apache.taglibs</groupId> <artifactId>taglibs-standard-spec</artifactId> <version>1.2.5</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.taglibs/taglibs-standard-impl --> <dependency> <groupId>org.apache.taglibs</groupId> <artifactId>taglibs-standard-impl</artifactId> <version>1.2.5</version> </dependency>
成功
整个目录结构
相关推荐
xiuyangsong 2020-11-16
Nishinoshou 2020-11-09
jimgreatly 2020-09-01
dongxurr 2020-08-18
Dullonjiang 2020-08-15
Dullonjiang 2020-08-11
Dullonjiang 2020-08-09
dongxurr 2020-08-08
yunzhonmghe 2020-08-07
jimgreatly 2020-08-03
Dullonjiang 2020-07-30
jimgreatly 2020-07-27
liqiancao 2020-07-26
xiuyangsong 2020-07-26
dongxurr 2020-07-26
mcvsyy 2020-07-26
helloxusir 2020-07-25
牧场SZShepherd 2020-07-20