SSM整合开发(SpringMVC + Spring + MyBatis)(初次开发)

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

首先,来理一下开发SSM项目的思路

  1. 使用springdb的mysql库,表使用student ( id auto_increment,name,age )

  2. 新建maven web项目

  3. 加入依赖
    springmvc , spring , mybatis三个框架的依赖,jackson依赖,mysql驱动,druid连接池
    jsp , servlet依赖

  4. 写web.xml
    1)注册DispatcherServlet
    目的: 1. 创建springmvc容器对象,才能创建Controller类对象。2.创建的是Servlet ,才能接受用户的请求。
    2)注册spring的监听器:ContextLoaderListener,目的:创建spring的容器对象,才能创建service , dao等对象。
    3)注册字符集过滤器,解决post请求乱码的问题

  5. 创建包,controller包, service , dao ,实体类包名创建好

  6. 写springmvc , spring , mybatis的配置文件
    1)springmvc配置文件
    2)spring配置文件
    3)mybatis主配置文件
    4)数据库的属性配置文件

  7. 写代码,dao接口和mapper文件,service和实现类,controller,实体类。

  8. 写jsp页面

1.搭建SSM开发环境

用maven创建一个新项目,并加入下列依赖:

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

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <!--spring事务-->
    <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>

    <!--mybatis依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.6</version>
    </dependency>
    <!--mysql驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.20</version>
    </dependency>

    <!--druid连接池-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.12</version>
    </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>

并在<build>标签中加入:

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

2.配置web.xml

2.1 注册 ContextLoaderListener 监听器

<!--注册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>

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

2.2 注册字符集过滤器

<!--注册声明过滤器,解决中文乱码的问题-->
  <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>

注册字符集过滤器,解决中文乱码的问题

2.3 配置中央调度器

  <!--注册中央调度器-->
  <servlet>
    <servlet-name>myweb</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>myweb</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

3.确定好项目结构

创建好相应的包及XML文件
在这里插入图片描述

4.编写配置文件

JDBC 属性配置文件 jdbc.properties

(根据自己的版本来写url,我用的是 8 版本,跟 5 版本的不一样)

jdbc.url=jdbc:mysql://localhost:3306/test01?&useSSL=false&serverTimezone=UTC
jdbc.username=root
jdbc.passwd=123456
jdbc.max=20

SpringMVC配置文件

<?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相关的对象-->
    <context:component-scan base-package="com.controller"/>

    <!--声明视图解析器-->
    <bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <mvc:annotation-driven/>
    <!--
        1.响应ajax请求,返回json
        2.解决静态资源访问问题。
    -->

</beans>

mybatis配置文件

<?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>
        设置日志,输出到控制台
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>-->

    <!--设置别名-->
    <typeAliases>
        <!--实体类所在的包名(也可以是其他的类)-->
        <package name="com.domain"/>
    </typeAliases>

    <!--
    name :是包名,这个包中的所有mapper.xml一次都能加载使用
    package的要求:
    1. mapper文件名称和dao接口名必须完全一样,包括大小写
    2. mapper文件和dao接口必须在同一目录
    -->
    <mappers>
        <package name="com.dao"/>
    </mappers>
</configuration>

5.定义实体类

跟数据库表信息保持一致

package com.domain;

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

6.定义Dao接口以及sql映射文件

Dao接口:

package com.dao;

import com.domain.Student;

import java.util.List;

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.dao.StudentDao">
    <select id="selectStudents" resultType="Student">
        select id,name,age from student order by id desc
    </select>

    <insert id="insertStudent">
        insert into student(name, age) values(#{name},#{age})
    </insert>
</mapper>
    

7.Service接口及其实现类

package com.service;

import com.domain.Student;

import java.util.List;

public interface StudentService {

    int addStudent(Student student);
    List<Student> findStudents();
}

接口实现类:

package com.service.impl;

import com.dao.StudentDao;
import com.domain.Student;
import com.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) {
        int num=studentDao.insertStudent(student);
        return num;
    }

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

8.定义处理器Controller

package com.controller;

import com.domain.Student;
import com.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.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

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

    @Autowired
    private StudentService service;

    //注册学生
    @RequestMapping("/addStudent.do")
    public ModelAndView addStudent(Student student){
        ModelAndView mv=new ModelAndView();
        String tips="注册失败";
        //调用service处理student
        System.out.println("11111");
        int num=service.addStudent(student);
        if(num>0){
            tips="学生【"+student.getName()+"】注册成功";
        }
        //添加数据
        mv.addObject("tips",tips);
        //指定结果页面
        mv.setViewName("result");

        return mv;
    }

    //处理查询,响应ajax
    @RequestMapping("/queryStudent.do")
    @ResponseBody
    public List<Student> queryStudent(){
        //参数检查,简单的数据处理
        List<Student> list= service.findStudents();
        return list;
    }
}

9.定义前端视图

首页index.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>index</title>
</head>
<body>
    <div align="center">
        <p>SSM整合例子</p>
        <img src="images/dress1.jpg"/>
        <table>
            <tr>
                <td><a href="addStudent.jsp">注册学生</a> </td>
            </tr>
            <tr>
                <td><a href="listStudent.jsp">浏览学生</a></td>
            </tr>
        </table>
    </div>
</body>
</html>

注册学生页面

<%
    String basePath = request.getScheme() + "://" +
            request.getServerName() + ":" + request.getServerPort() +
            request.getContextPath() + "/";
%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <base href="<%=basePath%>">
    <title>插入学生</title>

</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;&nbsp;</td>
                    <td><input type="submit" name="注册"></td>
                </tr>
            </table>

        </form>
    </div>
</body>
</html>

浏览学生页面

<%
    String basePath = request.getScheme() + "://" +
            request.getServerName() + ":" + request.getServerPort() +
            request.getContextPath() + "/";
%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>浏览学生</title>
    <base href="<%=basePath%>">
    <script type="text/javascript" src="js/jquery-3.3.1.js"></script>
    <script type="text/javascript">
        $(function () {
            loadStudentData();
            $("#btnLoader").click(function () {
                //单击按钮刷新
                loadStudentData();
            })
        })
        function loadStudentData() {
            $.getJSON({
                url:"student/queryStudent.do",
                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="btnLoader" value="刷新数据">
    </div>
</body>
</html>

注册结果页面


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    result.jsp 结果页面,注册结果: ${tips}
</body>
</html>

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值