SpringSSM是目前的主流框架之一,而所谓的SSM也就是指Spring+SpringMVC+mybatis三种框架的整合!
一、SpringSSM框架的搭建
(一)创建项目
然后起个名字一路next
(二)父项目处理
创建好父项目后,将src删掉,父项目不放相关代码,只负责版本控制等。
我使用了父项目进行版本控制,所以搭的是父类项目下的子module,父项目的pom依赖设置:
如果不想搭建父项目的话,可以直接把下面的配置中的<version>4.3.10.RELEASE</version>加到子类的Spring的dependency中
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>4.3.10.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<!-- 插件 -->
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
</configuration>
</plugin>
</plugins>
<!--设置maven拷贝那些目录下的文件-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
</build>
(二)创建子module中及添加其SSM框架所需依赖:
创建好后再子module的pom.xml中添加SSM框架所需的依赖:
<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>
</properties>
<dependencies>
<!-- spring相关的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<!--mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!--mybatis与spring整合依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!-- mysql数据库驱动依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<!--连接池 c3p0-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--日志-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<!--Servlet-api-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!--jsp-api-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.4</version>
</dependency>
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
<dependency>
<groupId>com.alipay.sdk</groupId>
<artifactId>alipay-sdk-java</artifactId>
<version>4.18.0.ALL</version>
</dependency>
</dependencies>
<build>
<finalName>SpringSSM_study_demo01</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
<!--设置maven拷贝那些目录下的文件-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
</build>
(三)在子module中的src下创建三个文件夹:
右键main->new->Directory,创建源码文件夹和资源配置文件夹
然后src右键->new->Directory
结果:
(四)创建applicationContext.xml,applicationContext-tx.xml,applicationContext-mapper.xml和springmvc.xml并配置。
①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">
<!--导入其他Spring配置文件-->
<import resource="classpath:applicationContext-mapper.xml"/>
<import resource="classpath:applicationContext-tx.xml"/>
<import resource="classpath:springmvc.xml"/>
</beans>
②applicationContext-tx.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context" 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">
<!--开始扫描注解-->
<context:component-scan base-package="com.shop.service"/>
<!--配置声明式事务管理-->
<!--配置一个事务管理器-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="txManager">
<!--配置事务策略: 对业务层的方法进行怎么样事务管理-->
<tx:attributes>
<!-- 对业务层类的具体的方法的设置事务策略
name: 业务层类的方法名, 支持通配符 *
要求你业务层类的方法必须按照你配置和名字起名
查询方法的策略
read-only: 是否只读: true只读, false不只读 默认值, 查询效率,对查询方法设置只读,
增删改方法,一定不能设置只读
propagation: 事务传播机制:
REQUIRED:默认值,表示如果存在一个事务,则支持当前事务,如果当前没有事务,则开启一个新的事务. 增删改
SUPPORTS:表示如果存在一个事务,则支持当前事务,如果当前没有事务,则按非事务方式执行, 查询
rollback-for="在那些异常下进行回滚" 默认值 RuntimeException
rollback-for="java.lang.Exception" 所有异常都回滚
no-rollback-for="那些异常不回滚"
timeout: 超时 默认 -1 永不超时
-->
<tx:method name="query*" read-only="true" propagation="SUPPORTS"/>
<tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
<tx:method name="select*" read-only="true" propagation="SUPPORTS"/>
<tx:method name="add*" rollback-for="java.lang.Exception"/>
<tx:method name="update*" rollback-for="java.lang.Exception"/>
<tx:method name="del*" rollback-for="java.lang.Exception"/>
<tx:method name="*" rollback-for="java.lang.Exception"/>
</tx:attributes>
</tx:advice>
<!--把事务通知类txAdvice与业务层的类方法进行织入: AOP的技术-->
<aop:config>
<!--配置切入点-->
<aop:pointcut id="mypointcut" expression="execution(* com.shop.service..*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="mypointcut"/>
</aop:config>
</beans>
③applicationContext-mapper.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:p="http://www.springframework.org/schema/p"
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">
<!--加载properties
如果是多个properties文件, 文件路径与文件路径使用逗号分割 classpath:db.properties,classpath:log4j.properties
-->
<context:property-placeholder location="classpath:db.properties" file-encoding="UTF-8"/>
<!--配置一个C3p0数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 数据库四大参数 -->
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
<!--连接池相关参数-->
<!-- 初始连接数 -->
<property name="initialPoolSize" value="${jdbc.initialPoolSize}"/>
<!-- 增量,每次创建几个连接 -->
<property name="acquireIncrement" value="${jdbc.acquireIncrement}"/>
<!-- 最大连接数 -->
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"/>
<!-- 最小连接数,默认值等于初始连接数 -->
<property name="minPoolSize" value="${jdbc.minPoolSize}"/>
</bean>
<!--配置SqlSessionFactoryBean-->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
<!--配置别名-->
<property name="typeAliasesPackage" value="com.shop.entity"/>
<!--加载sql映射文件 * 任意 一定要注意: classpath*: 如果不写, 后面*无效-->
<property name="mapperLocations" value="classpath*:mapper/*Mapper.xml"/>
</bean>
<!--配置mapper扫描器 扫描指定包下所有的Mapper接口
创建Mapper接口代理对象, sqlSession.getMapper()并且保存到Spring容器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--扫描那个包下Mapper接口-->
<property name="basePackage" value="com.shop.mapper"/>
<!--注入SqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"/>
</bean>
</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: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
http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven conversion-service="conversionService">
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<!--ContentType类型:告诉前端,后台响应的application/json,charset: 编码-->
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
<property name="objectMapper">
<bean class="com.fasterxml.jackson.databind.ObjectMapper">
<!-- 为null字段时不显示 -->
<property name="serializationInclusion">
<value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
</property>
<!--默认与属性名一样-->
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!--配置文件上传解析器
注意: id值一定是multipartResolver
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置最大的上传文件大小 :10M = 10 *1024*1024 B
单位 字节
-->
<property name="maxUploadSize" value="10485760"></property>
</bean>
<mvc:default-servlet-handler/>
<context:component-scan base-package="com.shop.Controller"/>
<!--配置转换器的服务-->
<!-- 自定义参数绑定 -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<!-- 指定自己定义的Converter类
内部bean, 只能在conversionService的bean内部有效
-->
<bean class="com.shop.converter.MyDateConverter"/>
<!--<bean class="com.fs.ssm.converter.MyIntegerConverter"/>-->
</set>
</property>
</bean>
</beans>
中途会有文件不存在报错,等等创建
结果:
(五)创建db.properties,log4j.properties
①db.properties:
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/shop?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
jdbc.user=root
jdbc.password=123456
jdbc.initialPoolSize=5
jdbc.acquireIncrement=3
jdbc.maxPoolSize=10
jdbc.minPoolSize=5
②log4j.properties
log4j.rootCategory=WARN, stdout
#开发过程中,日志输出级别DEBUG 打印更多信息,方便调试, 项目上线, 一定修改为INFO, 日志输出越多,性能越低
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %t %c{2}:%L - %m%n
log4j.category.org.springframework.beans.factory=DEBUG
结果:
(六)修改webapp/WEB-INF/web.xml:
然后回到web.xml进行配置:
<!--监听器-->
<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>
<!--前端控制器-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--Servlet的初始化参数, 只能在该Servlet获取-->
<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>
<!--请求的路径
1) /* 错误写法, 因为, /* 所有的请求都会经过前端控制器, 经过前端控制器, 根据url查找处理器
jsp页面.经过前端控制器, 查询jsp的url的处理器, 肯定找不到, 报错 处理器找不到
2) / Restfull 风格的写法, 所有的请求都会经过前端控制器,除以.jsp结尾的url, 静态资源(css,js,html,图片..)
经过前端控制器, 根据url查找处理器, 后期需要对静态资源过滤
3) *.do/*.action 以.do或者.action结尾的url经过前端控制
-->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 解决put,patch等请求,data数据拿不到的问题 -->
<filter>
<filter-name>HttpPutFormContentFilter </filter-name>
<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HttpPutFormContentFilter </filter-name>
<servlet-name>springmvc</servlet-name>
</filter-mapping>
(七)创建各类实体类
1.com.shop.Controller.UserController:
@RestController //该Controller全部返回JSON格式
@RequestMapping("/user/*")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/queryUserById")
public User queryUserById(User user){
return user;
}
}
2.com.shop.entity.User:
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@ToString
public class User {
private int u_id; //用户唯一id
private String u_name; //用户名
private String u_pwd; //用户密码
private int u_authority; //用户权限
private int u_age; //用户年龄
private String u_sex; //用户性别
private String u_location; //用户地址(可以为空但是购物前必须填写)
private String u_img;
private String u_introduction; //用户个人介绍
}
配置Tomcat:
启动tomcat,然后访问localhost:8088/user/queryUserById?u_id=1
到这里我们已经整合好SpringMVC了,剩下的就是把mybatis整合好就行!
3.com.shop.service.UserService(接口):
public interface UserService {
public User queryUserById(Integer id);
}
4.com.shop.service.impl.UserServiceImpl(实现类):
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User queryUserById(Integer id) {
return userMapper.queryUserById(id);
}
}
5.com.shop.mapper.UserMapper(接口):
public interface UserMapper {
User queryUserById(Integer id);
}
6.mapper.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">
<!-- 这里的namespace指的是这个mybatis所实现的接口的路径 -->
<mapper namespace="com.shop.mapper.UserMapper">
<select id="queryUserById" resultType="com.shop.entity.User">
select * from user where u_id=#{id}
</select>
</mapper>
然后我们修改UserController和UserServiceImpl:
@RestController //该Controller全部返回JSON格式
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/queryUserById")
public User queryUserById(User user){
User getUser = userService.queryUserById(user.getU_id());
return getUser;
}
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User queryUserById(Integer id) {
return userMapper.queryUserById(id);
}
}
然后我们启动tomcat,再次访问localhost:8088/user/queryUserById?u_id=1,得到结果:
好的,那么到这里SpringSSM框架就搭建完成啦!