SSM整合開發

山丘i發表於2020-08-19

一、整體思路

SSM: SpringMVC + Spring + MyBatis.

SpringMVC:檢視層,介面層,負責接收請求,顯示處理結果的。
Spring:業務層,管理service,dao,工具類物件的。
MyBatis:持久層, 訪問資料庫的

使用者發起請求--SpringMVC接收--Spring中的Service物件--MyBatis處理資料

SSM整合也叫做SSI (IBatis也就是mybatis的前身), 整合中有容器。

  1. 第一個容器SpringMVC容器, 管理Controller控制器物件的。
  2. 第二個容器Spring容器,管理Service,Dao,工具類物件的

我們要做的把使用的物件交給合適的容器建立,管理。 把Controller還有web開發的相關物件交給springmvc容器, 這些web用的物件寫在springmvc配置檔案中

service,dao物件定義在spring的配置檔案中,讓spring管理這些物件

springmvc容器和spring容器是有關係的,關係已經確定好了

springmvc容器是spring容器的子容器, 類似java中的繼承。 子可以訪問父的內容
在子容器中的Controller可以訪問父容器中的Service物件, 就可以實現controller使用service物件

實現步驟:

  1. 使用ssm的mysql庫, 表使用student(id auto_increment, name, age)

  2. 新建maven web專案

  3. 加入依賴

    springmvc,spring,mybatis三個框架的依賴,jackson依賴,mysql驅動,druid連線池
    jsp,servlet依賴

  4. 寫web.xml

    • 註冊DispatcherServlet ,目的:1.建立springmvc容器物件,才能建立Controller類物件。2.建立的是Servlet,才能接受使用者的請求。
    • 註冊spring的監聽器:ContextLoaderListener,目的: 建立spring的容器物件,才能建立service,dao等物件。
    • 註冊字符集過濾器,解決post請求亂碼的問題
  5. 建立包, Controller包, service ,dao,實體類包名建立好

  6. 寫springmvc,spring,mybatis的配置檔案

    • springmvc配置檔案
    • spring配置檔案
    • mybatis主配置檔案
    • 資料庫的屬性配置檔案
  7. 寫程式碼, dao介面和mapper檔案, service和實現類,controller, 實體類。

  8. 寫jsp頁面

二、SSM整合註解開發

需求:完成學生的註冊和資訊瀏覽

1. 建立Student

2. 建立Web工程

通過maven

3. maven依賴

<?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.md</groupId>
  <artifactId>07-ssm</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>



  <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>
  </properties>

  <dependencies>


    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>


    <!--servlet依賴-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <!-- jsp依賴 -->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2.1-b03</version>
      <scope>provided</scope>
    </dependency>

    <!--springmvc依賴-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.5.RELEASE</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.2.5.RELEASE</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>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.9</version>
    </dependency>

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.12</version>
    </dependency>

  </dependencies>



  <build>

    <resources>
      <resource>
        <directory>src/main/java</directory><!--所在的目錄-->
        <includes><!--包括目錄下的.properties,.xml 檔案都會掃描到-->
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>



  </build>
</project>

4. 定義程式結構

5. 編寫配置檔案

jdbc屬性配置檔案jdbc.properties

jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=123456
jdbc.maxActive=20

Spring配置檔案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: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="com.md.service"/>


    <!--宣告資料來源,連線資料庫-->
    <context:property-placeholder location="classpath:conf/jdbc.properties"/>
    <bean id="myDataSource" 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}" />
        <property name="maxActive" value="${jdbc.maxActive}" />
    </bean>






    <!--SqlSessionFactory-->
    <bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="myDataSource"/>
        <property name="configLocation" value="classpath:/conf/mybatis.xml"/>
    </bean>




    <!--建立 dao物件-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="SqlSessionFactory"/>
        <!--指定包名,包名是dao介面所在的包名,dao預設物件的名稱:是介面名字的首字母小寫-->
        <property name="basePackage" value="com.md.dao"/>
    </bean>


    <!--上面的這個是一個模板,只有一些配置檔案的路徑是根據自己建立寫的-->

</beans>

SpringMVC的配置檔案,dispatcherServlet.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 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相關的物件-->

    
    <!-- 註冊元件掃描器,指定@Controller註解所在的類-->
    <context:component-scan base-package="com.md.controller"/>



    <!-- 指定檢視解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>



    <!--註冊註解驅動
        1. 響應ajax請求,返回json
        2. 解決靜態資源訪問問題
    -->
    <mvc:annotation-driven/>



</beans>

mybatis的配置檔案 , 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>


    <!--<settings>-->
        <!--&lt;!&ndash;設定日誌&ndash;&gt;-->
        <!--<setting name="logImpl" value="STDOUT_LOGGING"/>-->
    <!--</settings>-->



    <!--設定別名,在mapper.xml檔案中,返回值不用在寫包名了,直接寫類名即可-->
    <typeAliases>
        <package name="com.md.domain"/>
    </typeAliases>


    <!-- sql對映檔案的位置 -->
    <mappers>

        <!--name是包名,這個包中所有mapper.xml一次載入
            使用package的要求
            1. mapper檔名稱和dao介面名稱必須完全一樣
            2. mapper檔案和dao介面必須在同一目錄
        -->
        <package name="com.md.dao"/>
    </mappers>

</configuration>

6. 定義web.xml

由於自動生成的是這樣的,版本太低,需要換成現在高的版本,直接把之前寫好的複製過來就行

換成這樣

  1. 註冊 ContextLoaderListener
  2. 註冊 DisatcherServlet
  3. 註冊字符集過濾器
  4. 同時建立 Spring 的配置檔案和 SpringMVC 的配置檔案(上面已經建立好了)
<?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">





  <!--註冊中央排程器-->

  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    <init-param>
      <param-name>contextConfigLocation</param-name>
      <!--自定義路徑-->
      <param-value>classpath:conf/dispatcherServlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>


  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>




  <!--註冊spring監聽器-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <!--自定義路徑-->
    <param-value>classpath:conf/applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>





  <!--註冊字符集過濾器-->
  <!--宣告過濾器,解決post請求亂碼的問題-->
  <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>

7. 實體類

package com.md.domain;

/**
 * @author MD
 * @create 2020-08-13 20:21
 */
public class Student {
    private Integer id;
    private String name;
    private Integer age;

    public Student() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

8. Dao介面和對映檔案

都在是dao包下,且檔名相同

package com.md.dao;

import com.md.domain.Student;

import java.util.List;

/**
 * @author MD
 * @create 2020-08-13 20:22
 */
public interface StudentDao {
    int insertStudent(Student student);

    List<Student> selectStudents();

}

StudentDao.xml

<?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="com.md.dao.StudentDao">
    <insert id="insertStudent" >
      insert into student(name,age) values(#{name} , #{age})
    </insert>

    <!--設定了別名,這裡返回值直接寫類名-->
    <select id="selectStudents" resultType="Student">

    select id, name , age from student

    </select>
</mapper>

9. Service介面和實現類

package com.md.service;

import com.md.domain.Student;

import java.util.List;

/**
 * @author MD
 * @create 2020-08-13 20:31
 */
public interface StudentService {

    int addStudent(Student student);

    List<Student> findStudents();

}

實現類

package com.md.service.impl;

import com.md.dao.StudentDao;
import com.md.domain.Student;
import com.md.service.StudentService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author MD
 * @create 2020-08-13 20:32
 */

@Service
public class StudentServiceImpl implements StudentService {

    // 引用資料型別的自動注入@Resource、@Autowired
    @Resource
    private StudentDao studentDao;



    @Override
    public int addStudent(Student student) {

        int nums = studentDao.insertStudent(student);
        return nums;
    }

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

10. 處理器

在controller包下

package com.md.controller;

import com.md.domain.Student;
import com.md.service.StudentService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author MD
 * @create 2020-08-13 20:37
 */

@Controller
@RequestMapping("/student")
public class StudentController {

    // 自動注入
    @Resource
    private StudentService service;

    // 註冊學生
    @RequestMapping("/addStudent.do")
    public ModelAndView addStudent(Student student){
        ModelAndView mv = new ModelAndView();
        String tips = "註冊失敗";
        // 呼叫service處理student
        int nums = service.addStudent(student);
        if (nums > 0){
            tips = "註冊成功";
        }

        // 新增資料,指定頁面
        mv.addObject("tips",tips);
        mv.setViewName("result");
        return mv;
    }



    // 處理查詢,響應ajax
    @RequestMapping("/queryStudent.do")
    @ResponseBody
    public List<Student> queryStudent(){

        List<Student> students = service.findStudents();

        // 會被框架轉為json的陣列
        return students;
    }


}

11. 首頁

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">

        <h2>SSM整合</h2>

        <table>
            <tr>
                <td> <a href="addStudent.jsp">學生註冊</a> </td>
            </tr>
            <br>
            <tr>
                <td><a href="listStudent.jsp">學生資訊</a> </td>
            </tr>
        </table>

    </div>

</body>
</html>

12. 註冊頁面

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;</td>
                    <td><input type="submit" value="注&nbsp;&nbsp;&nbsp;&nbsp;冊"></td>
                </tr>
            </table>
        </form>
    </div>


</body>
</html>

13. 註冊結果

在/WEB-INF/jsp/result.jsp

<%--
  Created by IntelliJ IDEA.
  User: MD
  Date: 2020/8/13
  Time: 20:45
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h1>註冊結果:${tips}</h1>

</body>
</html>

14. 瀏覽頁面

listStudent.jsp

<%--
  Created by IntelliJ IDEA.
  User: MD
  Date: 2020/8/13
  Time: 21:10
  To change this template use File | Settings | File Templates.
--%>
<%@ 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%>">
    <script type="text/javascript" src="js/jquery-3.4.1.js"></script>
    <script type="text/javascript" >
        $(function () {

            // 在當前的頁面載入後執行loadStudent函式
            loadStudent();

            $("#btn").click(function () {
                loadStudent();

            });
        });


        // 自定義函式
        function loadStudent() {
            $.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="btn" value="查詢資料">
    </div>
</body>
</html>

此時再配置Tomcat執行即可,之後再新增新的功能

相關文章