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

目录

  • 前言
  • 一、搭建 SSM 开发环境
    • Maven pom.xml
    • 配置 web.xml
  • 二、SSM 整合注解式开发
    • 建表
    • 定义包、组织程序的结构
    • 编写配置文件
    • 定义 web.xml
    • 实体类 Student
    • 定义 Dao 接口 与 sql 映射文件
    • 定义 Service 接口与实现类
    • 处理器定义
    • 定义视图-首页文件 --- index.jsp
    • 注册学生页面 --- addStudent.jsp
    • 浏览学生页面 --- listStudent.jsp
    • 注册成功与失败界面
  • 三、测试


前言

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

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


一、搭建 SSM 开发环境

Maven pom.xml

  • 依赖
 
<dependency>
  <groupId>javax.servletgroupId>
  <artifactId>javax.servlet-apiartifactId>
  <version>3.1.0version>
  <scope>providedscope>
dependency>

<dependency>
  <groupId>javax.servlet.jspgroupId>
  <artifactId>jsp-apiartifactId>
  <version>2.2.1-b03version>
  <scope>providedscope>
dependency>

<dependency>
  <groupId>org.springframeworkgroupId>
  <artifactId>spring-webmvcartifactId>
  <version>5.2.5.RELEASEversion>
dependency>

<dependency>
  <groupId>org.springframeworkgroupId>
  <artifactId>spring-txartifactId>
  <version>5.2.5.RELEASEversion>
dependency>

<dependency>
  <groupId>org.springframeworkgroupId>
  <artifactId>spring-jdbcartifactId>
  <version>5.2.5.RELEASEversion>
dependency>

<dependency>
  <groupId>org.springframeworkgroupId>
  <artifactId>spring-aspectsartifactId>
  <version>5.2.5.RELEASEversion>
dependency>

<dependency>
  <groupId>com.fasterxml.jackson.coregroupId>
  <artifactId>jackson-coreartifactId>
  <version>2.9.0version>
dependency>
<dependency>
  <groupId>com.fasterxml.jackson.coregroupId>
  <artifactId>jackson-databindartifactId>
  <version>2.9.0version>
dependency>

<dependency>
  <groupId>org.mybatisgroupId>
  <artifactId>mybatis-springartifactId>
  <version>1.3.1version>
dependency>

<dependency>
  <groupId>org.mybatisgroupId>
  <artifactId>mybatisartifactId>
  <version>3.5.1version>
dependency>

<dependency>
  <groupId>mysqlgroupId>
  <artifactId>mysql-connector-javaartifactId>
  <version>8.0.28version>
dependency>

<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
  <version>1.1.12version>
dependency>
  • 插件

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

<resources>
    <resource>
         <directory>src/main/javadirectory>
        <includes>
              <include>**/*.xmlinclude>
              <include>**/*.propertiesinclude>
        includes>
    resource>

   <resource>
        <directory>src/main/resourcesdirectory>
        <includes>
             <include>**/*.xmlinclude>
             <include>**/*.propertiesinclude>
        includes>
   resource>
resources>

配置 web.xml

  • 注册 ContextLoaderListener 监听器

<context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:applicationContext.xmlparam-value>
context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>

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

  • 注册字符集过滤器

<filter>
    <filter-name>charaterEncodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
        <param-name>encodingparam-name>
        <param-value>utf-8param-value>
    init-param>
    <init-param>
        <param-name>forceRequestEncodingparam-name>
        <param-value>trueparam-value>
    init-param>
    <init-param>
        <param-name>forceResponseEncodingparam-name>
        <param-value>trueparam-value>
    init-param>
filter>
<filter-mapping>
    <filter-name>charaterEncodingFilterfilter-name>
    <url-pattern>/*url-pattern>
filter-mapping>

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

  • 配置中央调度器

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


<servlet>
    <servlet-name>dispatcherServletservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:dispatcherServlet.xmlparam-value>
    init-param>
    <load-on-startup>1load-on-startup>
servlet>

<servlet-mapping>
    <servlet-name>dispatcherServletservlet-name>
    <url-pattern>*.dourl-pattern>
servlet-mapping>

二、SSM 整合注解式开发

项目:ssm

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

建表

建立 student 表

SpringMVC(三) --------- SSM 整合开发案例_第1张图片

定义包、组织程序的结构

SpringMVC(三) --------- SSM 整合开发案例_第2张图片

jsp文件

SpringMVC(三) --------- SSM 整合开发案例_第3张图片

编写配置文件

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


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

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

    
    <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


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

    
    <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


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>
    
    <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 映射文件


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>Titletitle>
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> 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>Titletitle>
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>   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>Titletitle>
head>
<body>
    <div align="center">
        <p>查询学生数据p>
        <table>
            <thead>
                <tr>
                    <td>idtd>
                    <td>姓名td>
                    <td>年龄td>
                tr>
            thead>
            <tbody id="stubody">tbody>
        table>
    div>
body>
html>

引入 JQuery

SpringMVC(三) --------- SSM 整合开发案例_第4张图片
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("").append("" + n.id + "").append("" + n.name + "").append("" + n.age + "").append("")
                })
            }
        })
    }
</script>

注册成功与失败界面

view 目录下的页面结构

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

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

三、测试

首页
SpringMVC(三) --------- SSM 整合开发案例_第5张图片
注册界面
SpringMVC(三) --------- SSM 整合开发案例_第6张图片
注册结果
SpringMVC(三) --------- SSM 整合开发案例_第7张图片
查询界面
SpringMVC(三) --------- SSM 整合开发案例_第8张图片

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

无红线即没有冲突
SpringMVC(三) --------- SSM 整合开发案例_第9张图片

你可能感兴趣的:(SpringMVC,java-ee,spring,java)