SpringMVC: End

张天宇 on 2020-04-22

SpringMVC第三篇,SSM的整合。

环境搭建

数据库的准备

1
2
3
4
5
6
7
create database ssm;
use ssm;
create table account(
id int primary key auto_increment,
name varchar(20),
money double
);

导入坐标

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
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.0.2.RELEASE</spring.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<mysql.version>5.1.6</mysql.version>
<mybatis.version>3.4.5</mybatis.version>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- spring -->
<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>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<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>
<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 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>

代码准备

  1. 实体类

    1
    2
    3
    4
    5
    6
    public class Account implements Serializable {
    private Integer id;
    private String name;
    private Double money;
    //getter & setter
    }
  2. 持久层

    1
    2
    3
    4
    public interface IAccountDao {
    public List<Account> findAll();
    public void saveAccount(Account account);
    }
  3. 业务层

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    public interface IAccountService {
    public List<Account> findAll();
    public void saveAccount(Account account);
    }
    public class AccountService implements IAccountService {
    @Override
    public List<Account> findAll() {
    System.out.println("业务层:输出所有");
    return null;
    }

    @Override
    public void saveAccount(Account account) {
    System.out.println("业务层:保存了");
    }
    }
  4. 控制器

    1
    2
    public class AccountController {
    }

Spring搭建

  1. 编写Spring配置文件applicationContext.xml,并导入依赖。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    <?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">
    <!-- 开启扫描,只处理Service和Dao,Controller交给SpringMVC处理 -->
    <context:component-scan base-package="top.tyzhang">
    <!-- 配置哪些不扫描 -->
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    </beans>
  2. 使用注解配置业务层。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    @Service("accountService")
    public class AccountService implements IAccountService {
    @Override
    public List<Account> findAll() {
    System.out.println("业务层:输出所有");
    return null;
    }
    //...
    }
  3. 测试Spring是否能独立运行。

    1
    2
    3
    4
    //加载Spring配置文件
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    AccountService as = (AccountService) applicationContext.getBean("accountService");
    as.findAll();

Spring整合SpringMVC

SpringMVC搭建

  1. 配置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
    <!DOCTYPE web-app PUBLIC
    "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd" >
    <web-app>
    <display-name>Archetype Created Web Application</display-name>
    <!-- 前端控制器 -->
    <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 加载springmvc.xml配置文件-->
    <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!-- 启动服务器,创建该Servlet-->
    <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>
    </web-app>
  2. 创建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
    <?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">
    <!-- 开启注解扫描,只扫描Controller-->
    <context:component-scan base-package="top.tyzhang">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!-- 配置视图解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/pages/"/>
    <property name="suffix" value=".jsp"/>
    </bean>
    <!-- 过滤静态资源-->
    <mvc:resources location="/css/" mapping="/css/**" />
    <mvc:resources location="/images/" mapping="/images/**" />
    <mvc:resources location="/js/" mapping="/js/**" />
    <!-- 开启注解的支持-->
    <mvc:annotation-driven/>
    </beans>
  3. 创建控制器类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    @Controller
    @RequestMapping("/account")
    public class AccountController {
    @RequestMapping("/findAll")
    public String findAll(){
    System.out.println("表现层:查询所有信息");
    return "list";
    }
    }
  4. 配置相应JSP文件,启动服务器测试。

    1
    <a href="account/findAll">查询所有</a>

整合

  1. 配置监听器实现启动服务创建容器。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <!-- 配置 spring 提供的监听器,用于启动服务时加载容器 。
    该间监听器只能加载 WEB-INF 目录中名称为 applicationContext.xml 的配置文件 -->
    <listener>
    <listener-class>
    org.springframework.web.context.ContextLoaderListener
    </listener-class>
    </listener>
    <!-- 手动指定 spring 配置文件位置 -->
    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
  2. 依赖注入

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    @Controller
    @RequestMapping("/account")
    public class AccountController {
    @Autowired
    private AccountService accountService;
    @RequestMapping("/findAll")
    public String findAll(){
    System.out.println("表现层:查询所有信息");
    accountService.findAll();
    return "list";
    }
    }

Spring整合MyBatis

搭建测试MyBatis环境

  1. 配置文件SqlMapConfig.xml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    <?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>
    <environments default="mysql">
    <environment id="mysql">
    <transactionManager type="JDBC"/>
    <dataSource type="POOLED">
    <property name="driver" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql:///ssm"/>
    <property name="username" value="root"/>
    <property name="password" value="root"/>
    </dataSource>
    </environment>
    </environments>
    <!-- 使用的是注解 -->
    <mappers>
    <!-- <mapper class="top.tyzhang.dao.IAccountDao"/> -->
    <!-- 该包下所有的dao接口都可以使用 -->
    <package name="top.tyzhang.dao"/>
    </mappers>
    </configuration>
  2. Dao中编写SQL语句。

    1
    2
    3
    4
    5
    6
    public interface IAccountDao {
    @Select("select * from account")
    public List<Account> findAll();
    @Insert("insert into account (name, money) values (#{name}, #{money})")
    public void saveAccount(Account account);
    }
  3. 测试。

    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
    public class MyBaTest {
    @Test
    public void run() throws IOException {
    //加载mybatis配置文件
    InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
    //创建SqlSessionFactory对象
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
    //创建SqlSession对象
    SqlSession session = factory.openSession();
    //获取代理对象
    IAccountDao accountDao=session.getMapper(IAccountDao.class);
    System.out.println(accountDao.findAll().size());
    session.close();
    in.close();
    }
    @Test
    public void run2() throws IOException {
    Account account = new Account();
    account.setName("lala");
    account.setMoney(14.0);
    //加载mybatis配置文件
    InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
    //创建SqlSessionFactory对象
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
    //创建SqlSession对象
    SqlSession session = factory.openSession();
    //获取代理对象
    IAccountDao accountDao=session.getMapper(IAccountDao.class);
    accountDao.saveAccount(account);
    //提交事务
    session.commit();
    System.out.println(accountDao.findAll().size());
    session.close();
    in.close();
    }
    }

整合

  1. SqlMapConfig.xml配置文件中的内容配置到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
    <?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">
    <!-- 开启扫描,只处理Service和Dao,Controller交给SpringMVC处理 -->
    <context:component-scan base-package="top.tyzhang">
    <!-- 配置哪些不扫描 -->
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- spring整合mybatis框架,就是把mybatis的配置文件交给spring-->
    <!-- 配置连接池-->
    <bean id="dSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    <property name="jdbcUrl" value="jdbc:mysql:///ssm"/>
    <property name="user" value="root"/>
    <property name="password" value="root"/>
    </bean>
    <!-- 配置工厂对象SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dSource"/>
    </bean>
    <!-- 配置接口所在的包-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="top.tyzhang.dao"/>
    </bean>
    </beans>
  2. 在IAccountDao接口中添加@Repository注解。

    1
    2
    3
    4
    5
    6
    7
    @Repository
    public interface IAccountDao {
    @Select("select * from account")
    public List<Account> findAll();
    @Insert("insert into account (name, money) values (#{name}, #{money})")
    public void saveAccount(Account account);
    }
  3. 在Service中注入Dao对象。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    @Service("accountService")
    public class AccountService implements IAccountService {
    @Autowired
    private IAccountDao iAccountDao;
    @Override
    public List<Account> findAll() {
    System.out.println("业务层:输出所有");
    return iAccountDao.findAll();
    }

    @Override
    public void saveAccount(Account account) {
    System.out.println("业务层:保存了");
    iAccountDao.saveAccount(account);
    }
    }
  4. Controller中注入Service。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    @Controller
    @RequestMapping("/account")
    public class AccountController {
    @Autowired
    private AccountService accountService;
    @RequestMapping("/findAll")
    public String findAll(Model model){
    System.out.println("表现层:查询所有信息");
    List<Account> accountList = accountService.findAll();
    model.addAttribute("list",accountList);
    return "list";
    }
    }
  5. 截止到现在,增删查还没有提交事务的操作,需要在applicationContext.xml进行声明式事务管理。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    <!--    配置声明式事务管理-->
    <!--配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dSource"/>
    </bean>
    <!-- 配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
    <tx:method name="find*" read-only="true"/>
    <tx:method name="*" isolation="DEFAULT"/>
    </tx:attributes>
    </tx:advice>
    <!-- 配置AOP增强-->
    <aop:config>
    <aop:advisor advice-ref="txAdvice" pointcut="execution(* top.tyzhang.service.impl.*Service.*(..))"/>
    </aop:config>
  6. 控制器

    1
    2
    3
    4
    5
    6
    7
    @RequestMapping("/save")
    public void save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
    System.out.println("表现层:保存");
    accountService.saveAccount(account);
    response.sendRedirect(request.getContextPath()+"/user/findAll");
    return;
    }