7. SSM 整合

空~2022年9月15日
  • SpringMVC
大约 6 分钟

7. SSM 整合

SSM: SpringMVC + Spring + MyBati

SpringMVC: 视图层, 界面层, 负责接收请求, 显示处理结果

Spring: 业务层, 管理 service, dao, 工具类对象

MyBatis: 持久层, 访问数据库

用户发起请求--SpringMVC 接收--Spring 中的 Service 对象--MyBatis 处理数据

实现步骤:

  1. 新建 mysql 库, 新建表 student(id auto_increment, name, age)

  2. 新建 maven web 项目, 加入依赖

    springmvc, spring, mybatis 三个框架的依赖, jackson 依赖, mysql 驱动, druid 连接池, jsp, servlet 依赖

  3. 写 web.xml

  4. 注册 DispatcherServlet

    1. 目的:
      1. 创建 springmvc 容器对象,才能创建 Controller 类对象。
      2. 创建的是 Servlet,才能接受用户的请求。
  5. 注册 spring 的监听器: ContextLoaderListener

    1. 目的:
      1. 创建 spring 的容器对象, 才能创建 service, dao 等对象。
      2. 注册字符集过滤器, 解决 post 请求乱码的问题
  6. 创建包, Controller 包, service, dao, 实体类包名创建好

  7. 写 springmvc, spring, mybatis 的配置文件

    1. springmvc 配置文件
    2. spring 配置文件
  8. mybatis 主配置文件

  9. 数据库的属性配置文件

  10. 写代码, dao 接口和 mapper 文件, service 和实现类, controller, 实体类。

  11. 写 jsp 页面

mysql 数据库

create table student
(
  id   int auto_increment
  primary key,
  name varchar(255) null,
  age  int          null
);

maven 依赖

<dependencies>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.8</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>5.2.5.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.8</version>
  </dependency>
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
  </dependency>
  <dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.2.1-b03</version>
    <scope>provided</scope>
  </dependency>
  <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.20</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-databind</artifactId>
    <version>2.9.0</version>
  </dependency>
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
  </dependency>
  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.6</version>
  </dependency>
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.7</version>
  </dependency>
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.6</version>
  </dependency>
</dependencies>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
  <!--注册spring的监听器-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:conf/spring.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--注册中央调度器-->
  <servlet>
    <servlet-name>servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:conf/springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>servlet</servlet-name>
    <url-pattern>*.do</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>
    <init-param>
      <param-name>forceRequestEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>forceResponseEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

创建包

20210817175421576_14204

编写配置文件

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?useSSL=true
jdbc.username=root
jdbc.password=root

mybatis.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>
  <!--类别名-->
  <typeAliases>
    <package name="demo.domain"/>
  </typeAliases>
  <mappers>
    <!--mapper映射文件-->
    <package name="demo.dao"/>
  </mappers>
</configuration>

applicationContext.xml

<?xml version="1.0" encoding="UTF8"?>
<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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           https://www.springframework.org/schema/context/spring-context.xsd">
  <!--spring配置文件: 声明service,dao,工具类等对象-->
  <!--声明service的注解@Service所在的包名位置-->
  <context:component-scan base-package="demo.service"/>

  <context:property-placeholder location="classpath:conf/jdbc.properties"/>
  <!--声明数据源,连接数据库-->
  <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
        init-method="init" destroy-method="close">
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
  </bean>
  <!--SqlSessionFactoryBean创建SqlSessionFactory-->
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="configLocation" value="classpath:conf/mybatis.xml"/>
  </bean>
  <!--声明mybatis的扫描器,创建dao对象-->
  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    <property name="basePackage" value="demo.dao"/>
  </bean>
  <!--事务配置:注解的配置, aspectj的配置-->
</beans>

springmvc.xml

<?xml version="1.0" encoding="UTF8"?>
<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
                           https://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/mvc
                           https://www.springframework.org/schema/mvc/spring-mvc.xsd">
  <!--springmvc配置文件, 声明controller和其它web相关的对象-->
  <context:component-scan base-package="demo.controller"/>
  <!--视图解析器-->
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/view/"/>
    <property name="suffix" value=".jsp"/>
  </bean>
  <!--
        1. 响应ajax请求,返回json
        2. 解决静态资源访问问题。
    -->
  <mvc:annotation-driven/>
</beans>

编写代码

domain 层

@Data
public class Student {
  private Integer id;
  private String name;
  private String age;
}

dao 层

public interface StudentDao {
    /**
   * 增加学生
   *
   * @param student 新学生
   * @return 受影响的行
   */
    int insertStudent(Student student);

    /**
   * 查询全部
   *
   * @return list
   */
    List<Student> selectStudents();
}
<?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">
<mapper namespace="demo.dao.StudentDao">
  <insert id="insertStudent">
    insert into ssm.student(name, age)
    values (#{name}, #{age});
  </insert>
  <select id="selectStudents" resultType="student">
    select id, name, age
    from ssm.student;
  </select>
</mapper>

service 层

public interface StudentService {
    /**
   * service
   *
   * @param student 新学生
   * @return 行
   */
    int addStudent(Student student);

    /**
   * 查询
   *
   * @return 全部
   */
    List<Student> queryStudents();
}
@Service(value = "StudentService")
public class StudentServiceImpl implements StudentService {

    @Resource private StudentDao studentDao;

    @Override
    public int addStudent(Student student) {
        return studentDao.insertStudent(student);
    }

    @Override
    public List<Student> queryStudents() {
        return studentDao.selectStudents();
    }
}

controller 层

@Controller
@RequestMapping("/student")
public class StudentController {
    @Resource private StudentService service;

    /**
   * 注册
   *
   * @param student 学生
   * @return 行
   */
    @RequestMapping("/addStudent.do")
    public ModelAndView addStudent(Student student) {
        ModelAndView mv = new ModelAndView();
        int addStudent = service.addStudent(student);
        if (addStudent > 0) {
            mv.addObject("msg", "添加成功");
            mv.setViewName("success");
        } else {
            mv.addObject("msg", "添加失败");
            mv.setViewName("fail");
        }
        return mv;
    }

    /**
   * 查询 响应ajax请求
   *
   * @return list
   */
    @RequestMapping("/queryStudent.do")
    @ResponseBody
    public List<Student> queryStudents() {
        return service.queryStudents();
    }
}

jsp 页面

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
  <%
     String basePath = request.getScheme() + "://" +
     request.getServerName() + ":" + request.getServerPort() +
     request.getContextPath() + "/";
     %>
    <html>
      <head>
        <title>功能入口</title>
        <base href="<%=basePath%>"/>
      </head>
      <body>
        <div align="center">
          <p>SSM整合的例子</p>
          <img src="images/ssm.jpg"/>
          <table>
            <tr>
              <td><a href="addStudent.jsp"> 注册学生</a></td>
            </tr>
            <tr>
              <td><a href="listStudent.jsp">浏览学生</a></td>
            </tr>
          </table>
        </div>
      </body>
    </html>

addStudent.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
  <%
     String basePath = request.getScheme() + "://" +
     request.getServerName() + ":" + request.getServerPort() +
     request.getContextPath() + "/";
     %>

    <html>
      <head>
        <title>注册学生</title>
        <base href="<%=basePath%>"/>
      </head>
      <body>
        <div align="center">
          <form action="student/addStudent.do" method="post">
            <table>
              <tr>
                <td>姓名:</td>
                <td><input type="text" name="name"></td>
              </tr>
              <tr>
                <td>年龄:</td>
                <td><input type="text" name="age"></td>
              </tr>
              <tr>
                <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
                <td><input type="submit" value="注册"></td>
              </tr>
            </table>
          </form>
        </div>
      </body>
    </html>

listStudent.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
  <%
     String basePath = request.getScheme() + "://" +
     request.getServerName() + ":" + request.getServerPort() +
     request.getContextPath() + "/";
     %>
    <html>
      <head>
        <title>查询学生ajax</title>
        <base href="<%=basePath%>"/>
        <script type="text/javascript" src="js/jquery-3.4.1.js"></script>
        <script type="text/javascript">
          $(function () {
            //在当前页面dom对象加载后,执行loadStudentData()
            loadStudentData();

            $("#btnLoader").click(function () {
              //loadStudentData();
              alert($("#country > option:selected").val());

              alert($("#country > option:selected").text());
            })
          })

          function loadStudentData() {
            $.ajax({
              url: "student/queryStudent.do",
              type: "get",
              dataType: "json",
              success: function (data) {
                //清除旧的数据
                $("#info").html("");
                //增加新的数据
                $.each(data, function (i, n) {
                  $("#info").append("<tr>")
                    .append("<td>" + n.id + "</td>")
                    .append("<td>" + n.name + "</td>")
                    .append("<td>" + n.age + "</td>")
                    .append("</tr>")

                })
              }
            })
          }
        </script>
      </head>
      <body>
        <div align="center">
          <table>
            <thead>
              <tr>
                <td>学号</td>
                <td>姓名</td>
                <td>年龄</td>
              </tr>
            </thead>
            <tbody id="info">

            </tbody>
          </table>
          <input type="button" id="btnLoader" value="查询数据">
          <select id="country">
            <option value="1">中国</option>
            <option value="2">俄罗斯</option>
            <option value="3">西班牙</option>
          </select>
        </div>
      </body>
    </html>

WEB-INF/view/success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
  <html>
    <head>
      <title>Title</title>
    </head>
    <body>
      成功
    </body>
  </html>

WEB-INF/view/fail.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
  <html>
    <head>
      <title>Title</title>
    </head>
    <body>
      失败
    </body>
  </html>