Spring MVC之——SSM整合

搭建整合环境

SSM整合MyBatis与Spring对应版本.png
详细信息可以进入以下网址查看
http://www.mybatis.org/spring/

整合说明:SSM整合可以使用多种方式,咱们选择XML + 注解的方式

整合的思路

  1. 先搭建整合的环境
  2. 先把Spring的配置搭建完成
  3. 再使用Spring整合SpringMVC框架
  4. 最后使用Spring整合MyBatis框架

ps:其实都无所谓啦。。。下面为了看起来不臃肿,代码不重复放出来

pom.xml配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
<dependencies>

<!-- spring + SpringMVC + Spring整合测试 + jdbc + 事务 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>

<!-- junit测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>

<!-- mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>

<!-- servlet依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>

<!-- jsp的jstl表达式依赖 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end -->

<!-- Mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- Mybatis用于整合Spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>

<!-- c3p0连接池 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>

<!-- jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>

log4j配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=info, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n


web.xml配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<!-- SpringMVC的入口是servlet,这里配置SpringMVC -->
<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:springmvc.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>

<!-- 配置解决中文乱码的过滤器 -->
<filter>
<filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


<!-- 配置Spring的监听器 -->
<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>

1、搭建Spring + Mybatis

  • Userdao类
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    package pres.liuhaoan.ssm.dao;

    import org.apache.ibatis.annotations.*;
    import org.springframework.stereotype.Repository;
    import pres.liuhaoan.ssm.domain.User;

    import java.util.List;

    /**
    * User表操作的Dao类
    */
    @Repository
    public interface UserDao {
    /**
    * 查询所有
    * @return user列表
    */
    @Select("select * from user")
    @Results(id = "userMap", value = {
    @Result(column = "username", property = "username"),
    @Result(column = "birthday", property = "birthday"),
    @Result(column = "sex", property = "sex"),
    @Result(column = "address", property = "address")})
    List<User> findAll();


    /**
    * 新增账户
    * @param user 用户实体类信息
    * @return 返回自增索引
    */
    @Insert("insert into user(username, birthday, sex, address) values(#{username}, #{birthday}, #{sex}, #{address})")
    @SelectKey(statement = {"select last_insert_id()"}, keyColumn = "id", keyProperty = "id", before = false, resultType = Integer.class)
    int insertUser(User user);
    }

  • UserService类
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    package pres.liuhaoan.ssm.service.impl;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.stereotype.Controller;
    import org.springframework.stereotype.Service;
    import pres.liuhaoan.ssm.dao.UserDao;
    import pres.liuhaoan.ssm.domain.User;
    import pres.liuhaoan.ssm.service.UserService;

    import java.util.List;

    @Service("userService")
    public class UserServiceImpl implements UserService {

    private final UserDao userDao;

    public UserServiceImpl(@Qualifier("userDao") UserDao userDao) {
    this.userDao = userDao;
    }

    @Override
    public List<User> findAll() {
    return userDao.findAll();
    }

    @Override
    public int insertUser(User user) {
    return userDao.insertUser(user);
    }
    }

  • jdbcConfig.properties配置文件
    1
    2
    3
    4
    username=root
    password=
    url=jdbc:mysql://localhost/test?characterEncoding=UTF-8
    driver=com.mysql.jdbc.Driver
  • applicationContext.xml文件
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    <?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:tx="http://www.springframework.org/schema/tx"
    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/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">


    <!-- 配置Spring容器的扫描注解 -->
    <context:component-scan base-package="pres.liuhaoan">
    <!--配置不扫描SpringMVC的控制器注解-->
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>




    <!-- 以下是整合Mybatis的配置 -->


    <!-- 配置c3p0数据源 -->
    <context:property-placeholder location="classpath:jdbcConfig.properties"></context:property-placeholder>
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="${driver}"></property>
    <property name="user" value="${username}"></property>
    <property name="password" value="${password}"></property>
    <property name="jdbcUrl" value="${url}"></property>
    </bean>

    <!-- 配置SqlSession的工厂 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 配置扫描dao的包 -->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="pres.liuhaoan.ssm.dao"/>
    </bean>


    <!-- 配置事务管理器 -->
    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置事务的通知 -->
    <tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">
    <tx:attributes>
    <tx:method name="*"/>
    <tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method>
    </tx:attributes>
    </tx:advice>

    <!-- 配置aop -->
    <aop:config>
    <!-- 配置切入点表达式 -->
    <aop:pointcut id="pt1" expression="execution(* pres.liuhaoan.ssm.service.impl.*.*(..))"/>
    <!-- 建立切入点和通知的关系 -->
    <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
    </aop:config>


    </beans>

2、搭建SpringMVC

  • StringToDateConverter类型转换器类
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    package pres.liuhaoan.ssm.utils;

    import org.springframework.core.convert.converter.Converter;

    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    /**
    * 自定义类型转换
    */
    public class StringToDateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String s) {
    System.out.println(s);
    DateFormat format = null;
    try {
    if(s == null) {
    throw new NullPointerException("请输入要转换的日期");
    }
    format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    return format.parse(s);
    } catch (Exception e) {
    throw new RuntimeException("输入日期有误");
    }
    }
    }

  • springmvc.xml配置文件
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    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
    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">

    <!-- 配置spring创建容器时要扫描的包 -->
    <context:component-scan base-package="pres.liuhaoan.ssm.controller">
    <!--<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>-->
    </context:component-scan>

    <!-- 配置视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/pages/"></property>
    <property name="suffix" value=".html"></property>
    </bean>


    <!-- 配置spring开启注解mvc的支持-->
    <mvc:annotation-driven conversion-service="converterService"></mvc:annotation-driven>

    <!-- 设置静态资源不过滤,方式一 -->
    <mvc:default-servlet-handler/>

    <!-- 设置静态资源不过滤,方式二-->
    <!--<mvc:resources location="/css/" mapping="/css/**"/> &lt;!&ndash; 样式 &ndash;&gt;
    <mvc:resources location="/images/" mapping="/images/**"/> &lt;!&ndash; 图片 &ndash;&gt;
    <mvc:resources location="/js/" mapping="/js/**"/> &lt;!&ndash; javascript &ndash;&gt;-->

    <!-- 配置自定义类型转换器 -->
    <bean id="converterService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
    <array>
    <bean class="pres.liuhaoan.ssm.utils.StringToDataConverter"></bean>
    </array>
    </property>
    </bean>

    </beans>
  • 前端index.html文件
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    </head>
    <body>
    hello
    <a href="user/findAll">查询所有</a>

    <form action="user/addUser" method="post">
    姓名:<input name="username" type="text">
    生日:<input name="birthday" type="text">
    性别:<input name="sex" type="text">
    地址:<input name="address" type="text">
    <input value="提交" type="submit">
    </form>
    </body>
    </html>