14-SSM整合
Posted rqy0526
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了14-SSM整合相关的知识,希望对你有一定的参考价值。
今日知识
1. Spring整合MyBatis
2. SSM普通整合
3. SSM整合(Spring和SpringMVC分离)
4. 纯JavaConfig的SSM
Spring整合MyBatis
1. 导包
<properties>
<spring.version>5.1.8.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>$spring.version</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.6</version>
</dependency>
<!--mybatis的spring支持包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!--连接数据库的四个包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>$spring.version</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<!--test-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>$spring.version</version>
</dependency>
</dependencies>
2. 创建UserMapper接口
public interface UserMapper
public User selectByPrimaryKey(int id);
3. 创建UserService接口
public interface UserService
public User selectByPrimaryKey(int id);
4. 创建UserMapperImpl实现类
@Component
public class UserServiceImpl implements UserService
@Autowired
UserMapper userMapper;
public User selectByPrimaryKey(int id)
return userMapper.selectByPrimaryKey(id);
5. UserMapper.xml创建
<mapper namespace="com.rqy.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.rqy.domain.User">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="username" jdbcType="VARCHAR" property="username" />
<result column="birthday" jdbcType="DATE" property="birthday" />
<result column="sex" jdbcType="CHAR" property="sex" />
<result column="address" jdbcType="VARCHAR" property="address" />
/resultMap>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
*
from user
where id = #id,jdbcType=INTEGER
</select>
</mapper>
6. application.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://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
http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.rqy"/>
<!--<mvc:annotation-driven/>-->
<!--数据源-->
<bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatisday01?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--1.1.2 配置sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<!--<property name="configLocation" value="classpath:SqlMapConfig.xml"/>-->
</bean>
<!--MapperFactoryBean,缺点每个mapper接口都要注册进来-->
<!--<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.rqy.mapper.UserMapper"/>
<!–sqlSessionFactory注入到mapper中,代替mapper实现类–>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>-->
<!--把整个mapper接口所在的包都注册进来-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--扫描包,取代了SqlMapConfig.xml mapper映射文件-->
<property name="basePackage" value="com.rqy.mapper"/>
<!--与上面不太一样-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
</beans>
7. 测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application.xml")
public class MyTest
@Autowired
UserService userService;
@Test
public void test()
User user = userService.selectByPrimaryKey(35);
System.out.println(user);
SSM普通整合
1. 导包(数据源的包采用的druid的,你也可以采用其他的额)
<properties>
<spring.version>5.1.8.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>$spring.version</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.6</version>
</dependency>
<!--mybatis的spring支持包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!--连接数据库-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>$spring.version</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.11</version>
</dependency>
<!--test-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>$spring.version</version>
</dependency>
<!--jackson-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.7</version>
</dependency>
</dependencies>
2. 创建UserMapper接口
public interface UserMapper
public User selectByPrimaryKey(int id);
3. 创建UserService接口
public interface UserService
public User selectByPrimaryKey(int id);
4. 创建UserMapperImpl实现类
@Component
public class UserServiceImpl implements UserService
@Autowired
UserMapper userMapper;
public User selectByPrimaryKey(int id)
return userMapper.selectByPrimaryKey(id);
5. UserMapper.xml创建
<mapper namespace="com.rqy.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.rqy.domain.User">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="username" jdbcType="VARCHAR" property="username" />
<result column="birthday" jdbcType="DATE" property="birthday" />
<result column="sex" jdbcType="CHAR" property="sex" />
<result column="address" jdbcType="VARCHAR" property="address" />
/resultMap>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
*
from user
where id = #id,jdbcType=INTEGER
</select>
</mapper>
6. application.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"
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-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<context:component-scan base-package="com.rqy"/>
<mvc:annotation-driven/>
<!--数据源-->
<bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatisday01?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--1.1.2 配置sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
</bean>
<!--把整个mapper接口所在的包都注册进来-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--扫描包,取代了SqlMapConfig.xml mapper映射文件-->
<property name="basePackage" value="com.rqy.mapper"/>
<!--与上面不太一样-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
7. Web.xml
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
8. UserController.java
@Controller
public class UserController
@Autowired
UserService userService;
@RequestMapping("user")
public @ResponseBody User query(int id)
User user = userService.selectByPrimaryKey(id);
System.out.println(user);
return user;
SSM整合(Spring和SpringMVC分离)
1. 导包(和上面一样)
2. 创建UserMapper接口(和上面一样)
3. 创建UserService接口(和上面一样)
4. 创建UserMapperImpl实现类(和上面一样)
5. UserMapper.xml创建(和上面一样)
6. application.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"
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-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<context:component-scan base-package="com.rqy">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--数据源-->
<bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatisday01?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--1.1.2 配置sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
</bean>
<!--把整个mapper接口所在的包都注册进来-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--扫描包,取代了SqlMapConfig.xml mapper映射文件-->
<property name="basePackage" value="com.rqy.mapper"/>
<!--与上面不太一样-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!--测试的bean,项目初始化的时候就会执行-->
<bean class="com.rqy.domain.SpringBean"/>
</beans>
7. application-mvc.xml
<!--扫描包这个配置在springmvc的容器中不能去掉-->
<context:component-scan base-package="com.rqy.controller">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<mvc:annotation-driven/>
<!--测试的bean,当有url请求的时候才会执行-->
<bean class="com.rqy.domain.MvcBean"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
8. Web.xml(分别把application.xml和application-mvc.xml配置进去)
<!--通过listner注册spring容器,父容器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application.xml</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
9. UserController.java
@Controller
public class UserController
@Autowired
UserService userService;
@RequestMapping("user")
public @ResponseBody User query(int id)
User user = userService.selectByPrimaryKey(id);
System.out.println(user);
return user;
纯JavaConfig的SSM整合
思想:
1. 取消了application.xml和application-MVC.xml以及web.xml,
2. 用了一个继承AbstractAnnotationConfigDispatcherServletInitializer的类来实现具体文件配置
1. AppInitialize继承AACDSi类的书写
public class AppInitialize extends AbstractAnnotationConfigDispatcherServletInitializer
//SpringConfig指的是spring配置文件
@Override
protected Class<?>[] getRootConfigClasses()
return new Class[]SpringConfig.class;
//SpringMvcConfig指的是springMvc配置文件
@Override
protected Class<?>[] getServletConfigClasses()
return new Class[]SpringMvcConfig.class;
//配置sevlet请求路径/就OK了
@Override
protected String[] getServletMappings()
return new String[]"/";
//配置编码过滤器
@Override
protected Filter[] getServletFilters()
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("utf-8");
return new Filter[]characterEncodingFilter;
2. SpringConfig类的书写
@Configuration
@ComponentScan(value = "com.rqy",
excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = Controller.class))
@EnableTransactionManagement
@EnableAspectJAutoProxy
public class SpringConfig
//dataSource,必要
@Bean
public DataSource druidDatasource()
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
druidDataSource.setUrl("jdbc:mysql://localhost:3306/mybatisday01");
druidDataSource.setUsername("root");
druidDataSource.setPassword("123456");
return druidDataSource;
//SqlSessionFactoryBean 必要
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource)
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
return sqlSessionFactoryBean;
//MapperScannerConfigurer 必要
@Bean
public MapperScannerConfigurer mapperScannerConfigurer()
MapperScannerConfigurer mapperScannerConfigurer =new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
mapperScannerConfigurer.setBasePackage("com.rqy.mapper");
return mapperScannerConfigurer;
//文件的上传的配置,有需要才配置
@Bean
public CommonsMultipartResolver multipartResolver()
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
commonsMultipartResolver.setMaxInMemorySize(5240000);
return commonsMultipartResolver;
//配置事务管理器,同时要开启注解
@Bean
public DataSourceTransactionManager transactionManager(DataSource dataSource)
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);
return dataSourceTransactionManager;
3. SpringMvcConfig配置需要实现WebMvcConfigurer接口
@EnableWebMvc
@ComponentScan(value = "com.rqy.controller",
includeFilters =@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = Controller.class) )
public class SpringMvcConfig implements WebMvcConfigurer
<!--实现date的转换开始-->
//注入本身已有的接口
@Autowired
ConfigurableConversionService conversionService;
//把自定义的conversionService重新注册到bean中
@Bean
//保证conversionService的唯一性
@Primary
public ConfigurableConversionService conversionService()
return conversionService;
//指定执行顺序
@PostConstruct
public void addConverters()
String2DateConverter string2DateConverter = new String2DateConverter();
conversionService.addConverter(string2DateConverter);
<!--实现date的转换结束-->
<!--实现过滤器的配置-->
@Override
public void addInterceptors(InterceptorRegistry registry)
registry.addInterceptor(new MyFirstInterceptor());
//registry.addInterceptor().addPathPatterns("/abc/**");
<!--实现静态资源的配置-->
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
registry.addResourceHandler("/pic/**").addResourceLocations("file:D:/pic/");
registry.addResourceHandler("/pic/**").addResourceLocations("classpath:/pic/");
registry.addResourceHandler("/pic/**").addResourceLocations("/WEB-INF/pic");
//配置视图解析器
@Bean
public InternalResourceViewResolver internalResourceViewResolver()
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setPrefix("/WEB-INF/views/");
internalResourceViewResolver.setSuffix(".jsp");
return internalResourceViewResolver;
4. 导包
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.8.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--aspectj-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!--mybatis对spring的支持包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!--数据源和mysql驱动-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.11</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.8.RELEASE</version>
</dependency>
<!--test-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.8.RELEASE</version>
</dependency>
<!--jackson-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.7</version>
</dependency>
<!--文件上传的包-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
</dependencies>
5. 日期格式的转换
public class String2DateConverter implements Converter<String,Date>
@Override
public Date convert(String s)
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
try
Date date=sdf.parse(s);
return date;
catch (ParseException e)
e.printStackTrace();
return null;
6. 过滤器的实现
public class MyFirstInterceptor implements HandlerInterceptor
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
System.out.println("preHandle");
return true;
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception
System.out.println("postHandle");
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception
7. 创建UserMapper接口(和上面一样)
8. 创建UserService接口(和上面一样)
9. 创建UserMapperImpl实现类(和上面一样)
10. UserMapper.xml创建(和上面一样)一般通过你工程来完成
11. UserController测试类
@Controller
public class UserController
@Autowired
UserService userService;
@RequestMapping("user")
@ResponseBody
public User query(int id, Model model)
User user = userService.selectByPrimaryKey(id);
model.addAttribute("user",user.toString());
return user;
以上是关于14-SSM整合的主要内容,如果未能解决你的问题,请参考以下文章