这篇文章主要是ssm整合介绍,末尾有源码地址
创建一个ssm项目
首先使用IDEA创建一个基于maven的web项目,创建完成后有如下结构,完整的项目目录如下
注意java和resources文件夹颜色,如果不一致需要按如下处理
选中java右键选择Make Directory as->Sources Root;java文件夹的颜色会发生变化
同样选中resources文件夹Make Directory as->Resources Root
pom文件
<?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.ssmtest</groupId> <artifactId>ssmtest</artifactId> <version>1.0</version> <packaging>war</packaging> <name>ssmtest</name> <!-- 参数配置 --> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <spring.version>5.3.1</spring.version> <log4j2.version>2.17.1</log4j2.version> </properties> <dependencies> <!--pring相关上下文context--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <!--切面aspects--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <!--springMvc--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!--mybatis依赖以及spring整合mybatis依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency> <!--pagehelper分页插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.2.0</version> </dependency> <!--mysql+连接池+事务管理器--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.23</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.49</version> </dependency> <!--因为事务管理器DataSourceTransactionManager在这个依赖中,所以引入,但是持久层用的是mybatis不是jdbc--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <!--文件上传(只是上传没有下载)依赖--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <!--处理json数据--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.3</version> </dependency> <!--如果用thymeleaf作为模板 spring和thymeleaf依赖--> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>3.0.15.RELEASE</version> </dependency> <!--如果用jsp作为模板,引入以下jstl+jsp--> <!--<dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency>--> <!--日志记录spring5 框架自带了通用的日志封装,但是我们依然可以整合其他的日志框架使用,比如 Log4j。 不过在 spring5 中移除了 Log4jConfigListener,需要使用 Log4j2--> <!--日志门面--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.30</version> </dependency> <!--提供商是log4j官方,这个是log4j和slf4j的桥接器,spring是通过slf4j输出日志的, 依赖桥接器的实现,版本这里尤为重要,必须与log4j的依赖版版本一致--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>${log4j2.version}</version> </dependency> <!--log4j依赖log4j-core、log4j-api、log4j-web--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>${log4j2.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>${log4j2.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-web</artifactId> <version>${log4j2.version}</version> </dependency> <!--spring整合junit的依赖,在普通测试环境下,当需要使用Spring时,需要手动加载Spring配置, 且手动从 Spring容器中获取对象,使用Spring Test后,只需要通过注解指定Spring配置类, 在Spring容器中的对象均可自动装配--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <!--==================junit==================--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> </dependencies> </project>
jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.master.url=jdbc:mysql://localhost:3306/test jdbc.master.username=root jdbc.master.password=root jdbc.master.maxActive=10 jdbc.master.minIdle=5 jdbc.master.maxWait=10000
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" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--扫描组件(配置controller层)--> <context:component-scan base-package="com.ssmtest"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--加载数据库配置--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--配置连接池--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.master.url}"/> <property name="password" value="${jdbc.master.password}"/> <property name="username" value="${jdbc.master.username}"/> <property name="maxActive" value="${jdbc.master.maxActive}"/> <property name="maxWait" value="${jdbc.master.maxWait}"/> <property name="minIdle" value="${jdbc.master.minIdle}"/> </bean> <!--配置sqlSessionFactoryBean,将SqlSessionFactoryBean配置到ioc容器中,就可以在容器中直接获取SqlSessionFactory对象--> <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="classpath:mybatis-config.xml"/><!--配置mybatis全局配置文件--> <property name="dataSource" ref="dataSource"/><!--注入数据库连接池--> <property name="typeAliasesPackage" value="com.ssmtest.entity"/><!--类型别名所对应的包--> <property name="mapperLocations" value="classpath:mapper/*.xml"/><!--扫描mapper,mapper接口和xml包不一致时才设置--> <property name="plugins"> <set> <!--配置pageHelper 分页插件--> <bean class="com.github.pagehelper.PageInterceptor"> <property name="properties"> <props> <!--方言:--> <prop key="helperDialect">mysql</prop> </props> </property> </bean> </set> </property> </bean> <!--mapper接口扫描,将指定包下的所有mapper接口通过sqlSession创建代理实现类对象, 并将这些对象交给ioc容器,所有直接可以在service层注入mapper接口--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ssmtest.mapper"/> </bean> <!--=================事务配置开始======================--> <!--首先配置事务管理器,事务有两种方式(基于注解或者xml方式)--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--数据源--> <property name="dataSource" ref="dataSource"/> </bean> <!--将@Transactional标记的方法或类的所有方法进行事务管理--> <tx:annotation-driven transaction-manager="transactionManager"/> <!--xml方式--> <!--<!–编写事务通知 –> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="*" propagation="REQUIRED" isolation="DEFAULT" read-only="false" /> </tx:attributes> </tx:advice> <!– 编写AOP,让spring自动将事务切入到目标切点 –> <aop:config> <!– 定义切点 –> <aop:pointcut id="txPointcut" expression="execution(* com.xiaochen.dao.*.*(..))" /> <!– 将事务通知与切入点组合 –> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" /> </aop:config>--> <!--=================事务配置结束======================--> </beans>
springmvc.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 http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--springMVC只需扫描controller就可以--> <context:component-scan base-package="com.ssmtest.controller"/> <!-- jsp视图解析器- --> <!--<bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/views/"/> <property name="suffix" value=".jsp"/> <property name="exposeContextBeansAsAttributes" value="true"/> </bean>--> <!--thymeleaf视图解析器--> <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver"> <property name="order" value="1"/> <property name="characterEncoding" value="UTF-8"/> <property name="templateEngine"> <bean class="org.thymeleaf.spring5.SpringTemplateEngine"> <property name="templateResolver"> <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver"> <property name="prefix" value="/view/"/> <property name="suffix" value=".html"/> <property name="templateMode" value="HTML5"/> <property name="characterEncoding" value="UTF-8"/> </bean> </property> </bean> </property> </bean> <!--配置默认的servlet处理静态资源,https://blog.csdn.net/codejas/article/details/80055608--> <mvc:default-servlet-handler /> <!--开启mvc注解驱动(处理访问已经存在的controller路径,没有的又上面的默认servlet处理)--> <mvc:annotation-driven/> <!--配置试图控制器(当请求/时候,返回index试图)--> <mvc:view-controller path="/" view-name="index"/> <!--文件上传解析器 id必须是multipartResolver--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 最大可上传的文件大小 单位:byte 超出后会抛出MaxUploadSizeExceededException异常,可以异常解析器捕获 --> <property name="maxUploadSize" value="1048576"/> </bean> <!--拦截器(有需要的话配置)--> <!--异常解析器(有需要的话配置)--> </beans>
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> <!--配置全局属性--> <settings> <!--使用数据库的useGenerateKeys获取递增的主键值--> <setting name="useGeneratedKeys" value="true"/> <!--使用别名默认true--> <setting name="useColumnLabel" value="true"/> <!--将下划线映射为驼峰配置--> <setting name="mapUnderscoreToCamelCase" value="true"/> <!--返回map结果是值为null的字段确实问题--> <setting name="callSettersOnNulls" value="true"/> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> </configuration>
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="WARN"> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> </Console> </Appenders> <Loggers> <Root level="error"> <AppenderRef ref="Console"/> </Root> </Loggers> </Configuration>
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_3_1.xsd" version="3.1"> <!--==================spring编码过滤器,在第一行, 1. encoding:指定字符集,如UTF-8。 2. forceEncoding:response的字符集是否也使用encoding指定的值,为boolean类型。 当forceEncoding为false时表示: request.setCharacterEncoding(encoding); 为true表示: request.setCharacterEncoding(encoding); response.setCharacterEncoding(encoding); --> <filter> <description>spring编码过滤器</description> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <description>字符集编码</description> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--====================请求方式的过滤器,浏览器form表单只支持Get和POST请求,而Delete、Put等method并不支持。 Spring3.0添加了过滤器HiddenHttpMethodFilter,可以将这些请求转换为标准的http方法,使得支持GET、POST、PUT和DELETE请求--> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--=====================配置 springmvc前端控制器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:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup><!--将DispatcherServlet初始化时间提前到服务器启动时--> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--====================配置spring监听器,服务器启动时加载spring配置文件获取ioc容器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> </web-app>
UserMapper.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="com.ssmtest.mapper.UserMapper"> <!--因为配置了typeAliasesPackage,类型别名所对应的包 所以这里resultType直接可以写User--> <select id="list" resultType="User"> <!--配置了mapUnderscoreToCamelCase 将下划线映射为驼峰配置,不需写列别名对应--> select * from user </select> </mapper>
UserServiceImpl
@Service @Transactional public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public List<User> list(){ return userMapper.list(); } }
UserController
@RestController @RequestMapping("user") public class UserController { private static final Logger log = LoggerFactory.getLogger(UserController.class); @Autowired private UserService userService; @GetMapping("list") public PageInfo<User> list(Integer pageNum, Integer pageSize) { if (pageNum == null) { pageNum = 1; } if (pageSize == null) { pageSize = 10; } PageHelper.startPage(pageNum, pageSize); List<User> list = userService.list(); PageInfo<User> pricePageInfo = new PageInfo<>(list); return pricePageInfo; } }
user
public class User { private Integer id; private String userName; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } }
拓展
没有整合之前使用mybatis步骤如下
public void search(){ //加载mybatis的配置文件 InputStream input = User.class.getClassLoader().getResourceAsStream("mybatis.xml"); //或者用这种方法加载配置文件,Resources是mybatis自己提供的类 // InputStream inputStream = Resources.getResourceAsStream("mybatis.xml"); // 用建造者模式,创造 生产SqlSession的工厂(这个工厂的类型由配置文件决定) SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(input); // 工厂生产Sqlsession SqlSession sqlSession = factory.openSession(); //执行sql,根据sql的类型选择是用select、insert、delete、update方法执行sql //如果要修改数据库,最后要执行sqlSession.commit(),因为mybatis默认开启事务 // selectOne有两个重载方法,一参和二参(二参的是在sql语句里多了一个可变参数) UseMapper mapper = sqlSession.getMapper(UseMapper.class); List<User> users = mapper.list(); System.out.println(zs); //关闭IO资源(工厂对象会自动回收) input.close(); sqlSession.close(); }
当引入依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
并且在applicationContext.xml将SqlSessionFactoryBean配置到ioc容器中,就可以在容器中直接获取SqlSessionFactory对象,那上面的步骤可简化为
//容器中已经有了SqlSessionFactory 直接注入使用就行 @Autowired private SqlSessionFactory sqlSessionFactory; public void search(){ SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<String> list = mapper.list(); }
源码地址
源码同时提供了一条公用servise业务代码
下载完之后,只需要配置自己得数据源&在自己创建得数据库里创建一个user表,表字段含有id、user_name即可