0
点赞
收藏
分享

微信扫一扫

SpringMVC框架从入门到入土(三):SSM的整合开发

zibianqu 2022-04-23 阅读 59

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>
    <!--servlet依赖-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <!--jsp依赖-->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2.1-b03</version>
    </dependency>
    <!--spring的ioc依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.16</version>
    </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>
    <!--jdbc的依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <!--使用jquery进行操作-->
    <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>
    <!--mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.9</version>
    </dependency>
    <!--mybatis和spring的集成依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>
    <!--mysql数据库-->
    <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的配置文件

    <!--springmvc的配置文件,声明controller和其他web相关对象-->
    <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>

    <!--加入注解驱动
      1. 响应ajax请求,返回json
      2. 解决静态资源的问题
    -->
    <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的配置文件

       <!--spring的配置文件-->

       <!--声明数据库配置数据源-->
       <context:property-placeholder location="classpath:conf/jdbc.properties"/>

       <!--声明数据源DataSource,作用是连接数据库-->
       <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource"
             init-method="init" destroy-method="close">
              <!--set注入给DuridDataSource提供的数据库信息-->
              <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>

       <!--声明的是mybatis提供的SqlSessionFactory类,这个类内部创建SqlSessionFactory的-->
       <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
              <property name="dataSource" ref="myDataSource"/>
              <property name="configLocation" value="classpath:conf/mybatis.xml"/>
       </bean>

       <!--声明mybatis的扫描器MapperScannerConfigurer创建dao接口的代理对象-->
       <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
              <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
              <property name="basePackage" value="com.liar.dao"/>
       </bean>


       <!--声明service的注解@Service所在的类-->
       <context:component-scan base-package="com.liar.service"/>

mybatis的主配置文件

    <!--设置别名-->
    <typeAliases>
        <package name="com.liar.entity"/>
    </typeAliases>


    <!--sql mapper(sql映射文件)的位置-->
    <mappers>
        <!--
           name是包名,是这个包中所有mapper.xml一次都能加载
           要求:1. mapper文件要和dao接口必须完全一样,包括大小写
                2. mapper文件和dao接口必须在同一个目录下面
        -->
        <package name="com.liar.dao"/>
    </mappers>

写接口和实现类

dao包

  • StudentDao接口
public interface StudentDao {

    /**
     * 添加学生
     * @param student
     * @return
     */
    int insertStudent(Student student);

    /**
     * 查询学生
     * @return
     */
    List<Student> selectStudents();
}
  • mapper文件
<?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包

  • StudentService接口
    /**
     * 添加学生
     * @param student
     * @return
     */
    int addStudent(Student student);

    /**
     * 查找学生
     * @return
     */
    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;

/**
 * @author liar
 * @date 编写时间: 2022/4/17 18:32
 */
@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;

/**
 * @author liar
 * @date 编写时间: 2022/4/17 18:35
 */
@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 = "注册失败!";
        //调用service
        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;
    }
}

前端

  • index主页面
<%@ 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>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</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>
举报

相关推荐

0 条评论