SpringMVC(三) --------- SSM 整合开发案例


前言

SSM 编程,即 SpringMVC + Spring + MyBatis 整合,是当前最为流行的 JavaEE 开发技术架构。其实 SSM 整合的实质,仅仅就是将 MyBatis整合入 Spring。因为 SpringMVC原本就是Spring的一部分,不用专门整合。

SSM 整合的实现方式可分为两种:基于 XML 配置方式,基于注解方式。


一、搭建 SSM 开发环境

Maven pom.xml

  • 依赖
 <!--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>
<!--aspectj 依赖-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aspects</artifactId>
  <version>5.2.5.RELEASE</version>
</dependency>
<!--jackson-->
<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>
<!--mybatis 和 spring 整合的-->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>1.3.1</version>
</dependency>
<!--mybatis-->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.1</version>
</dependency>
<!--mysql 驱动-->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>8.0.28</version>
</dependency>
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
  <version>1.1.12</version>
</dependency>
  • 插件

用来定义除了 .java 文件之外,其他资源文件位置,放在 <bulid/>

<resources>
    <resource>
         <directory>src/main/java</directory>
        <includes>
              <include>**/*.xml</include>
              <include>**/*.properties</include>
        </includes>
    </resource>

   <resource>
        <directory>src/main/resources</directory>
        <includes>
             <include>**/*.xml</include>
             <include>**/*.properties</include>
        </includes>
   </resource>
</resources>

配置 web.xml

  • 注册 ContextLoaderListener 监听器
<!-- 注册 spring 的监听器  -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

注册 ServletContext 监听器的实现类 ContextLoaderListener,用于创建 Spring 容器及将创建好的 Spring 容器对象放入到 ServletContext 的作用域中。

  • 注册字符集过滤器
<!-- 注册字符集过滤器 -->
<filter>
    <filter-name>charaterEncodingFilter</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>charaterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

注册字符集过滤器,用于解决请求参数中携带中文时产生乱码问题。

  • 配置中央调度器

配置中央调度器时需要注意,SpringMVC 的配置文件名与其它 Spring 配置文件名不相同。这样做的目的是 Spring 容器创建管理 Spring 置文件中的 bean, SpringMVC 容器中负责视图层 bean 的初始化。

<!-- 注册 springmvc 的中央调度器  -->
<servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:dispatcherServlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

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

二、SSM 整合注解式开发

项目:ssm

需求:完成学生注册和信息浏览

建表

建立 student 表

在这里插入图片描述

定义包、组织程序的结构

在这里插入图片描述

jsp文件

在这里插入图片描述

编写配置文件

JDBC 属性配置文件 db.properties

在这里插入图片描述

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT
user=root
password=aszhuo123

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">
    <!-- 注册组件扫描器    -->
    <context:component-scan base-package="com.fancy.service"></context:component-scan>

    <!-- 引入属性配置文件   -->
    <context:property-placeholder location="db.properties"></context:property-placeholder>

    <!-- 配置阿里的Druid数据库连接池    -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url" value="${url}"></property>
        <property name="username" value="${user}"></property>
        <property name="password" value="${password}"></property>
    </bean>

    <!-- 注册 SqlSessionFactoryBean   -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="mybatis.xml"></property>
    </bean>

    <!-- 动态代理对象   -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
        <property name="basePackage" value="com.fancy.dao"></property>
    </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.alibaba.com/schema/stat"
       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.alibaba.com/schema/stat http://www.alibaba.com/schema/stat.xsd">

    <!-- 注册组件扫描器
         base-package : 指定 @Controller 注解所在包
    -->
    <context:component-scan base-package="com.fancy.controller"></context:component-scan>

   <!--  指定视图解析器   -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀与后缀   -->
        <property name="prefix" value="/WEB-INF/view"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    
    <!-- 注册注解驱动  -->
    <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>
    <!--  配置别名  -->
    <typeAliases>
        <package name="com.fancy.domain"/>
    </typeAliases>
    <!-- 指定sql映射文件    -->
    <mappers>
        <package name="com.fancy.dao"/>
    </mappers>
</configuration>

定义 web.xml

分为以下四步

1)注册 ContextLoaderListener
2)注册 DisatcherServlet
3)注册字符集过滤器
4)同时创建 Spring 的配置文件和 SpringMVC 的配置文件

我们之前已经定义好了

实体类 Student

package com.fancy.domain;

public class Student {
    
    private Integer id;
    private String name;
    private int age;

    public Student() {
    }

    public Student(Integer id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    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 int getAge() {
        return age;
    }

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

定义 Dao 接口 与 sql 映射文件

Dao 接口

package com.fancy.dao;

import com.fancy.domain.Student;

import java.util.List;

public interface StudentDao {
    int insertStudent(Student student);
    List<Student>  selectAllStudents();
}

sql 映射文件

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

    <select id="selectStudentByPage" resultType="Student">
        select id, name, age from student order by id  desc 
    </select>
</mapper>

定义 Service 接口与实现类

Service 接口

package com.fancy.service;

import com.fancy.domain.Student;

import java.util.List;

public interface StudentService {
    int addStudent(Student student);
    List<Student> findStudents();
}

Service 实现类

package com.fancy.service;

import com.fancy.dao.StudentDao;
import com.fancy.domain.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service(value = "studentService")
public class StudentServiceImpl implements StudentService {

    // 引用类型 @Autowired , @Resource, byType | byName
    // byType
    @Autowired
    private StudentDao stuDao;

    @Override
    public int addStudent(Student student) {
        return stuDao.insertStudent(student);
    }
    
    @Override
    public List<Student> findStudents(){
        return stuDao.selectAllStudents();
    }
}

处理器定义

package com.fancy.controller;

import com.fancy.domain.Student;
import com.fancy.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/student")
public class StudentController {
   @Autowired
   private StudentService studentService;

   @RequestMapping("/addStudent.do")
    public ModelAndView addStudent(Student student) {
       ModelAndView mv = new ModelAndView();
       // 调用 Service 处理业务, 将结果放入到 ModelAndView 中
       int rows = studentService.addStudent(student);
       if (rows > 0) {
           mv.addObject("msg", "注册成功");
           mv.setViewName("success");
       } else {
           mv.addObject("msg", "注册失败");
           mv.setViewName("fail");
       }
       return mv;
   }
}

定义视图-首页文件 — index.jsp

指定路径

<% String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"; %>

指定base标签

<base href="<%=basePath%>">

页面总代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<% String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"; %>
<html>
<head>
    <base href="<%=basePath%>">
    <title>Title</title>
</head>
<body>
      <div align="center">
          <p>SSM整合开发 -- 实现 student 表的操作</p>
          <img src="images/ssm.jpg">
          <table cellpadding="0" cellspacing="0">
              <tr>
                  <td><a href="addStudent.jsp">注册学生</a></td>
              </tr>
              <tr>
                  <td>&nbsp;</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" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <div align="center">
        <p>学生注册界面</p>
        <form action="/MyWeb/student/addStudent.do">
            <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; </td>
                    <td><input type="submit" value="注册"></td>
                </tr>
            </table>
        </form>
    </div>
</body>
</html>

浏览学生页面 — listStudent.jsp

页面代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <div align="center">
        <p>查询学生数据</p>
        <table>
            <thead>
                <tr>
                    <td>id</td>
                    <td>姓名</td>
                    <td>年龄</td>
                </tr>
            </thead>
            <tbody id="stubody"></tbody>
        </table>
    </div>
</body>
</html>

引入 JQuery

在这里插入图片描述
js 发起 ajax

<script type="text/javascript">
    $(function (){
        stuinfo();
    })
    function stuinfo() {
        $.ajax({
            url:"student/queryStudent.do",
            type:"post",
            dataType:"json",
            success:function (resp) {
                $("#stubody").html("");
                $.each(resp, function(i, n){
                    $("#stubody").append("<tr>").append("<td>" + n.id + "</td>").append("<td>" + n.name + "</td>").append("<td>" + n.age + "</td>").append("</tr>")
                })
            }
        })
    }
</script>

注册成功与失败界面

view 目录下的页面结构

在这里插入图片描述
success.jsp 页面

在这里插入图片描述
fail.jsp 页面
在这里插入图片描述

三、测试

首页
在这里插入图片描述
注册界面
在这里插入图片描述
注册结果
在这里插入图片描述
查询界面
在这里插入图片描述

如果出现 500 错误,检查 maven 依赖是否冲突

无红线即没有冲突
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

在森林中麋了鹿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值