SpringMVC框架从入门到入土(三):SSM的整合开发
 
SSM整合开发的实现步骤
 
SSM整合开发
SpringMVC + Spring + Mybatis
SpringMVC:视图层,界面层,负责接收请求,显示处理结果1
Spring:业务层,管理service,dao,工具类
Mybatis:持久层,访问数据库
工作流程:
用户发起请求--------使用SpringMVC接收--------Spring中的Service对象--------Mybatis处理数据
SSM整合也叫SSI,整合中有2个容器
1. SpringMVC的容器,管理Controller控制器对象
2. Spring容器,管理Service,Dao,工具类对象的
我们要做的就是把使用的对象交给合适的容器创建,管理。把Controller还有web开发的相关对象交给SpringMVC
这些web用的对象写在springmvc的配置文件中
service,dao对象写在spring配置文件中,让spring管理这些对象。
springmvc和spring容器有关系,关系已经确定了
springmvc和spring容器的子容器,类似java中的继承,就可以实现controller使用的service对象
实现步骤:
0. 使用springdb的数据库,表使用student(id,name,email,age)其中id自增
1. 新建maven项目
2. 加入依赖
   springmvc、spring、mybatis三个框架的依赖,jackson依赖,mysql驱动,druid连接池
   jsp,servlet依赖
3. 写web.xml
   ①注册DispatchServlet 目的:1. 创建springmvc容器对象,才能创建Controller类对象
                             2. 创建的是Servlet,才能接收用户的请求
   ②注册spring的监听器:ContextLoaderListener 目的:创建spring容器,才能创建service,到对象
   ③注册字符集过滤器,解决post请求的乱码问题
4. 创建包,Controller包,service,dao,实体类包名创建好
5. 写springmvc,spring,mybatis的配置文件
   ①springmvc的配置文件
   ②spring的配置文件
   ③mybatis的主配置文件
   ④数据库的属性配置文件
6. 写代码,dao接口和mapper文件,service文件
 
导入依赖
 
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2.1-b03</version>
    </dependency>
    
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.16</version>
    </dependency>
    
    <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.8</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.8</version>
    </dependency>
    
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.9</version>
    </dependency>
    
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</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.1.12</version>
    </dependency>
 
 
<build>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
  </build>
 
编写Web.xml文件
 
 
    
    <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>/</url-pattern>
    </servlet-mapping>
 
 
    <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>
 
 
    <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>
 
编写配置文件
 
springmvc的配置文件
 
    
    <context:component-scan base-package="com.liar.controller"/>
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    
    <mvc:annotation-driven/>
    
    <mvc:default-servlet-handler/>
 
数据库连接资源配置文件
 
jdbc.url=jdbc:mysql://localhost:3306/springdb?characterEncoding=UTF8&useSSL=false
jdbc.username=root
jdbc.password=001204
jdbc.maxActive=20
 
spring的配置文件
 
       
       
       <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>
       
       <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
              <property name="dataSource" ref="myDataSource"/>
              <property name="configLocation" value="classpath:conf/mybatis.xml"/>
       </bean>
       
       <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
              <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
              <property name="basePackage" value="com.liar.dao"/>
       </bean>
       
       <context:component-scan base-package="com.liar.service"/>
 
mybatis的主配置文件
 
    
    <typeAliases>
        <package name="com.liar.entity"/>
    </typeAliases>
    
    <mappers>
        
        <package name="com.liar.dao"/>
    </mappers>
 
写接口和实现类
 
dao包
 
 
public interface StudentDao {
    
    int insertStudent(Student student);
    
    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="com.liar.dao.StudentDao">
    
    <select id="selectStudents" resultType="com.liar.entity.Student">
        select id, name, email, age
        from student
        order by id desc
    </select>
    
    <insert id="insertStudent">
        insert into student(name, email, age)
        values (#{name}, #{email}, #{age})
    </insert>
</mapper>
 
service包
 
 
    
    int addStudent(Student student);
    
    List<Student> findStudents();
 
 
package com.liar.service.impl;
import com.liar.dao.StudentDao;
import com.liar.entity.Student;
import com.liar.service.StudentService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class StudentServiceImpl implements StudentService {
    
    @Resource
    private StudentDao studentDao;
    @Override
    public int addStudent(Student student) {
        return studentDao.insertStudent(student);
    }
    @Override
    public List<Student> findStudents() {
        return studentDao.selectStudents();
    }
}
 
controller包
 
package com.liar.controller;
import com.liar.entity.Student;
import com.liar.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;
@Controller
@RequestMapping("/student")
public class MyController {
    @Resource
    private StudentService service;
    
    @RequestMapping(value = "/addStudent.do")
    public ModelAndView addStudent(Student student){
        ModelAndView mv = new ModelAndView();
        String message = "注册失败!";
        
        int nums = service.addStudent(student);
        if(nums > 0){
            
            message = student.getName() + "注册成功!";
        }
        
        mv.addObject("message",message);
        
        mv.setViewName("result");
        return mv;
    }
    
    @RequestMapping(value = "/queryStudent.do")
    @ResponseBody
    public List<Student> queryStudent(Student student){
        
        List<Student> students = service.findStudents();
        return students;
    }
}
 
前端
 
 
<%@ 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>
     </div>
     <div align="center">
         <img  src="images/door.jpg" width="100px" height="50px"/>
     </div>
     <table align="center">
         <tr>
             <td><a href="addStudent.jsp">注册学生</a></td>
         </tr>
         <tr>
             <td><a href="listStudent.jsp">浏览学生</a></td>
         </tr>
     </table>
</body>
</html>
 
 
<%@ 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>
<h3 align="center">添加学生</h3>
<hr/>
<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="email"></td>
            </tr>
            <tr>
                <td>年龄:</td>
                <td><input type="text" name="age"></td>
            </tr>
            <tr>
                <td>     </td>
                <td><input type="submit" value="注册"></td>
            </tr>
        </table>
    </form>
</div>
</body>
</html>
 
 
<%@ 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="application/javascript" src="js/jquery-3.6.0.js"></script>
    <script type="application/javascript">
        $(function (){
            //在当前页面dom对象加载后直接执行
            loadStudentDate();
            $("#btnLoader").click(function (){
                loadStudentDate();
            })
        })
        function loadStudentDate(){
            $.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.email+"</td>")
                            .append("<td>"+n.age+"</td>")
                            .append("</tr>")
                    })
                }
            })
        }
    </script>
</head>
<body>
<div align="center">
    <table>
        <thead>
        <tr>
            <td>学号</td>
            <td>姓名</td>
            <td>邮件</td>
            <td>年龄</td>
        </tr>
        </thead>
        <tbody id="info">
        </tbody>
    </table>
    <input type="button" id="btnLoader" value="查询事件">
</div>
</body>
</html>
 
 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>结果页面</title>
</head>
<body>
<h5 align="center">结果页面</h5>
<hr/>
<h6 align="center">注册结果:${message}</h6>
</body>
</html>