SSM框架整合

1 - 搭建整合环境

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

2. 整合的思路

  1. 先搭建整合的环境

  2. 先把Spring的配置搭建完成

  3. 再使用Spring整合SpringMVC框架

  4. 最后使用Spring整合MyBatis框架

3. 创建数据库和表结构

create database ssm;
use ssm;
create table account(
    id int primary key auto_increment,
    name varchar(20),
    money double
);

4. 创建maven的工程,pom.xml文件中引入坐标依赖

<?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.howie</groupId>
  <artifactId>day03_ssm</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>day03_ssm Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <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.2.5.RELEASE</spring.version>
    <slf4j.version>1.7.22</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
    <mysql.version>8.0.19</mysql.version>
    <mybatis.version>3.4.5</mybatis.version>
  </properties>

  <dependencies>
    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>compile</scope>
    </dependency>
    <!-- spring -->
    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.5</version>
      <scope>runtime</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
    <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>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-test
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.2.5.RELEASE</version>
      <scope>test</scope>
    </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>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.1</version>
      <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl -->
    <dependency>
      <groupId>javax.servlet</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>
    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
      <scope>test</scope>
    </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.1</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.12</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>day03_ssm</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>
    <resources>
      <resource>
        <directory>src/main/java</directory><!--所在的目录-->
        <!--包括目录下的.properties,.xml 文件都会扫描到-->
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <!--filtering 选项 false 不启用过滤器, *.property 已经起到过滤的作用了-->
        <filtering>false</filtering>
      </resource>
    </resources>
  </build>
</project>
pom.xml

5. 编写实体类(com.howie.domain)

package com.howie.domain;

import java.io.Serializable;

/**
 * 用户
 */
public class User implements Serializable {
    private Integer id;
    private String username;
    private Double balance;

    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;
    }

    public Double getBalance() {
        return balance;
    }

    public void setBalance(Double balance) {
        this.balance = balance;
    }
}
User.java

6. 编写dao接口

package com.howie.dao;

import com.howie.domain.User;

import java.util.List;

/**
 * 用户dao接口
 */
public interface UserDao {
    // 查询所有用户信息
    public List<User> findAll();
    // 保存用户信息
    public int saveUser(User user);
}
UserDao.java

7. 编写service接口和实现类

package com.howie.service;

import com.howie.domain.User;

import java.util.List;

public interface UserService {
    // 查询所有用户信息
    public List<User> findAll();
    // 保存用户信息
    public int saveUser(User user);
}
UserService.java
package com.howie.service.impl;

import com.howie.domain.User;
import com.howie.service.UserService;
import org.springframework.stereotype.Service;

import java.util.List;
@Service("userServiceImpl") // <bean id="userServiceImpl" class="com.howie.service.impl.UserServiceImpl"><!bean>
public class UserServiceImpl implements UserService {
    @Override
    public List<User> findAll() {
        System.out.println("业务层:查询所有的用户信息。");
        return null;
    }

    @Override
    public int saveUser(User user) {
        System.out.println("业务层:保存账户。");
        return 0;
    }
}
UserServiceImpl.java

2 - 搭建和测试Spring的开发环境

1. 在ssm_web项目中创建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:contex="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的配置文件-->
    <!--开启注解扫描。controller包里面的逻应该由springMVC完成,不需要spring去管理,所以只需要扫描service与dao即可-->
    <contex:component-scan base-package="com.howie">
        <!--配置那些注解不扫描-->
        <contex:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </contex:component-scan>
</beans>
applicationContext.xml

2. 在ssm_web项目中编写测试方法,进行测试

package com.howie.ssm_test;

import com.howie.service.impl.UserServiceImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {
    @Test
    public void serviceTest(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserServiceImpl service = context.getBean("userServiceImpl",UserServiceImpl.class);
        service.findAll();
    }
}
SpringTest

 

3 - 搭建和测试SpringMVC的开发环境(spring整合springMVC)

1. 在web.xml中配置DispatcherServlet前端控制器。在web.xml中配置DispatcherServlet过滤器解决中文乱码

<!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>
  
  <!--配置解决中文乱码的过滤器-->
  <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的监听器。默认值加载WEB-INF目录下的applicationContext.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>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--加载spring-mvc.xml配置文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.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>
</web-app>
web.xml

2.创建spring-mvc.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.howie">
        <!--配置只扫描的注解-->
        <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>
    <!--过滤静态资源文件-->
    <!--
        DispatcherServlet会拦截到所有的资源,导致一个问题就是静态资源(img、css、js)也会被拦截到.
        所以要配置前端控制器,不需要拦截的静态资源
    -->
    <mvc:resources location="/css/" mapping="/css/**"/> <!-- 样式 -->
    <mvc:resources location="/images/" mapping="/images/**"/> <!-- 图片 -->
    <mvc:resources location="/js/" mapping="/js/**"/> <!-- javascript -->
    <!--开启springMVC注解的支持-->
    <mvc:annotation-driven/>
</beans>
spring-mvc.xml

3. 测试SpringMVC的框架搭建是否成功

  1. 编写index.jsp和list.jsp编写,超链接

  2. 创建UserController类,编写方法,进行测试

4.Spring整合SpringMVC的框架。 目的:在controller中能成功的调用service对象中的方法。

  1.在项目启动的时候,就去加载applicationContext.xml的配置文件,在web.xml中配置 ContextLoaderListener监听器(该监听器只能加载WEB-INF目录下的applicationContext.xml的配置文 件)

<!-- 配置Spring的监听器 -->
<listener>
    <listener-    class>org.springframework.web.context.ContextLoaderListener</listenerclass>
</listener>
<!-- 配置加载类路径的配置文件 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>
View Code

  2. 在controller中注入service对象,调用service对象的方法进行测试

package com.howie.controller;

import com.howie.domain.User;
import com.howie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 用户web
 */
@Controller
@RequestMapping(path = "/user")
public class UserController {
    /**
     * 查询所有用户信息
     */
    @Autowired  // UserService userService = new UserServiceImpl();
    private UserService userService;
    @RequestMapping(path = "/findAll")
    public String findAll(Model model){
        System.out.println("表现层:查询所有用户信息。。。");
        // 调用UserService的方法
        List<User> userList = userService.findAll();
        model.addAttribute("userList",userList); // 最终会存储到request域对象里
        return "list";
    }
    /**
     * 添加用户
     */
    @RequestMapping(path = "/saveUser")
    public void saveUser(String username, String balance, HttpServletResponse response, HttpServletRequest request) throws IOException {
        User user = new User();
        user.setId(3);
        user.setUsername(username);
        user.setBalance(Double.parseDouble(balance));
        int count = userService.saveUser(user);
        System.out.println(request.getContextPath());
        if(count == 1){
            response.sendRedirect(request.getContextPath()+"/user/findAll");
        }
    }
}
UserController.java

4 - 搭建和测试MyBatis的环境(spring整合MyBatis)

1. 在web项目中编写SqlMapConfig.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>
    <properties resource="db.properties"/> <!--加载文件内容-->
    <!--为mapper映射文件的domain器别名-->
    <typeAliases>
        <!--
            方式1:为指定的类分别起别名,别名的命名由我们来决定
            <typeAlias type="com.howie.domain.Province" alias="pd"/>
            type:要为那个domain起别名,填写包.类名称
            alias:别名的名字
        -->
        <!--
            方式2:使用package标签批量起别名
            别名是MyBatis默认为我们取好的,命名不是由我们自己决定,别名为类(类名的字母不区分大小写)
            name:指定一个包结构,表示在该包下,所有的domain自动起好了别名
        -->
        <package name="com.howie.domain"/>
        <package name="com.howie.vo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/> <!--事务管理-->
            <dataSource type="POOLED"> <!--数据源,连接池等-->
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--<mapper resource="org/mybatis/example/BlogMapper.xml"/>-->
        <!--Mapper映射文件注册-->
        <!--方式1:使用resource属性-->
        <!--方式2:使用class属性,找到dao层接口的全路径-->
        <!--<mapper class="com.howie.dao.ProvinceDao"/>-->
        <!--方式3:批量注册。name属性:指向dao层的包,表示在该dao包下,所有的mapper映射文件自动注册,推荐使用-->
        <package name="com.howie.dao"/>
    </mappers>
</configuration>
SqlMapConfig.xml

2. 在UserDao接口的方法上添加注解,编写SQL语句

package com.howie.dao;

import com.howie.domain.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 用户dao接口
 */
@Repository
public interface UserDao {
    // 查询所有用户信息
    @Select("select * from springdb.user_db")
    public List<User> findAll();
    // 保存用户信息
    @Insert("insert into springdb.user_db(id,username,balance) values(#{id},#{username},#{balance})")
    public int saveUser(User user);
}
UserDao.java

3. 编写测试的方法

    @Test
    public void testMyBatis() throws IOException {
        // 加载配置文件
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        // 创建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        // 创建SqlSession对象
        SqlSession session = factory.openSession();
        // 获取代理对象
        UserDao dao = session.getMapper(UserDao.class);
        // 查询所有数据
        List<User> userList = dao.findAll();
        for(User user:userList){
            System.out.println(user);
        }
        session.close();
        in.close();
    }
View Code

4.Spring整合MyBatis框架 。目的:把SqlMapConfig.xml配置文件中的内容配置到applicationContext.xml配置文件中

<!--spring整合MyBatis框架-->
    <!--引入外部属性文件-->
    <context:property-placeholder location="classpath:db.properties"/>
    <!--配置连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${prop.driverClass}"/>
        <property name="url" value="${prop.url}"/>
        <property name="username" value="${prop.username}"/>
        <property name="password" value="${prop.password}"/>
    </bean>
    <!--配置SqlSessionFactory工厂-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--配置UserDao接口所在包-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.howie.dao"/>
    </bean>
View Code

5. 在UserDao接口中添加@Repository注解

6. 在service中注入dao对象,进行测试

最终代码:https://github.com/laizhenghua2/ssm-template

 

posted @ 2020-09-22 09:47  赖正华  阅读(73)  评论(0编辑  收藏  举报