SSM整合——简单的小项目实战[通俗易懂]

SSM整合——简单的小项目实战[通俗易懂]文章目录:1.SSM整合思路1.1两个容器的创建1.2SSM整合开发的步骤2.SSM整合开发2.1项目的大体结构2.2使用Navicat创建一个表(student2)2.3IDEA中使用maven创建一个web项目2.4在pom.xml文件中添加相关依赖2.5在web.xml文件中。声明容器对象2.6创建项目中特定的包(entity、dao、service、controller)2.7编写mybatis、spring、springmvc的…

大家好,又见面了,我是你们的朋友全栈君。

文章目录:

1.SSM整合思路

1.1 两个容器的创建 

1.2 SSM整合开发的步骤

2.SSM整合开发 

2.1 项目的大体结构 

2.2 使用Navicat创建一个表(student2) 

2.3 IDEA中使用maven创建一个web项目

2.4 在pom.xml文件中添加相关依赖

2.5 在web.xml文件中。声明容器对象

2.6 创建项目中特定的包(entity、dao、service、controller)

2.7 编写mybatis、spring、springmvc的配置文件 

2.7.1 mybatis 

2.7.2 spring

2.7.3 springmvc

2.8 编写Java代码(实体类、dao接口和对应的mapper文件、service类、controller类)

2.8.1 创建一个实体类 

2.8.2 创建实体类对应的dao接口和接口对应的mapper文件 

2.8.3 创建dao接口对应的service接口和实现类

2.8.4 创建一个控制器类(接收并处理请求)

2.9 创建视图文件(jsp)

2.9.1 首页(index.jsp)

2.9.2 注册学生页面(addStudent.jsp)

2.9.3 注册成功和失败的页面(success.jsp、fail.jsp)

2.9.4 查询学生页面(queryStudent.jsp)

2.10 为项目配置tomcat,启动测试!!!

2.10.1 注册学生的测试结果 

2.10.2 查询学生的测试结果 

3.写在结尾!!!


1.SSM整合思路

SSM:Spring + SpringMVC + MyBatis,就是使用这三个框架的优势功能来完成一些项目的构建。三个框架分别对应了三层架构中的每一层。Spring: 业务逻辑层;SpringMVC:视图层;MyBatis:持久层。

SSM整合了话,就需要把对象交给容器,让容器去创建项目中要使用的Java对象,目前有两个容器。

第一个:Spring容器,Spring容器管理的是service和dao等对象,是业务逻辑层对象的容器。

第二个:SpringMVC容器,这个容器管理的是控制器对象,也就是视图层的对象。

1.1 两个容器的创建 

Spring容器的创建:在web.xml文件中声明 监听器 ContextLoaderListener 这个功能框架中已经写好了,就是创建Spring的容器对象 WebApplicationContext,在创建 WebApplicationContext 对象时,读取Spring的配置文件,遇到<bean>标签或者注解,就可以创建service、dao等对象,这些对象最终都放在Spring容器中。

SpringMVC容器的创建:在web.xml文件中声明 中央调度器 DispatcherServlet,在这个servlet的 init() 方法中,创建了容器对象WebApplicationContext,在创建 WebApplicationContext 对象时,读取SpringMVC的配置文件,如果遇到相应的注解,则创建控制器对象,创建好的对象放在SpringMVC容器中。

SSM整合——简单的小项目实战[通俗易懂]

1.2 SSM整合开发的步骤

  • 使用Navicat创建一个要操作的表。(也可以直接在IDEA中写sql语句来创建)
  • IDEA中使用maven创建一个web项目。
  • 在pom.xml文件中添加相关依赖。(spring、spring事务、springmvc、mybatis、mybatis-spring、mysql驱动、servlet、jsp、jackson、druid) 
  • 在web.xml文件中声明容器对象

         1)声明spring的监听器 ContextLoaderListener:创建spring容器对象(service、dao)。

         2)声明springmvc的中央调度器 DispatcherServlet:创建springmvc容器对象(controller)。

         3)声明字符集过滤器 CharacterEncodingFilter,解决post请求乱码的问题。

  • 创建项目中特定的包:entity、dao、service、controller。(package)
  • 编写mybatis配置文件、spring配置文件、springmvc配置文件。(xml)
  • 编写Java代码:实体类、dao接口和对应的mapper文件、service类、controller类,使用注解声明对象、给对象赋值。
  • 创建视图文件。(各种 jsp 页面,发起请求)
  • 启动 tomcat,测试!!!

2.SSM整合开发 

2.1 项目的大体结构 

SSM整合——简单的小项目实战[通俗易懂]

在这个SSM整合开发的项目中,用到了这些内容(JavaSE就不多说了。。。Java Web相关的有:JDBC、HTML、JS、json、jQuery、Ajax、Tomcat、Servlet、JSP、EL,最后是框架:MyBatis、Spring、SpringMVC) 。

2.2 使用Navicat创建一个表(student2) 

SSM整合——简单的小项目实战[通俗易懂]

2.3 IDEA中使用maven创建一个web项目

SSM整合——简单的小项目实战[通俗易懂]

2.4 在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>
    <!-- jackson依赖 -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.0</version>
    </dependency>
    <!-- spring依赖 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</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>
    <!-- springmvc依赖 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <!-- mybatis依赖 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</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.9</version>
    </dependency>
    <!-- druid连接池依赖 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.12</version>
    </dependency>

2.5 在web.xml文件中。声明容器对象

<!-- 声明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>
<!-- 声明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:/conf/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>
<!-- 声明字符集过滤器 -->
<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.6 创建项目中特定的包(entity、dao、service、controller

2.7 编写mybatis、spring、springmvc的配置文件 

2.7.1 mybatis 

jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&amp;characterEncoding=utf-8
jdbc.username=root
jdbc.password=12345678
<?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>

    <mappers>
        <!-- 加载dao包下的所有mapper文件 -->
        <package name="com.songzihao.dao"/>
    </mappers>
</configuration>

2.7.2 spring

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

    <!-- spring配置文件:声明service、dao、工具类、事务配置 -->
    <!-- 加载外部属性配置文件 -->
    <context:property-placeholder location="classpath:/conf/jdbc.properties" />

    <!-- 声明组件扫描器 -->
    <context:component-scan base-package="com.songzihao.service" />

    <!-- 创建数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <!-- 创建SqlSessionFactory对象 -->
    <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:/conf/mybatis.xml" />
    </bean>
    <!-- 创建SqlSession对象,通过反射机制加载dao接口对应的mapper文件 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="factory" />
        <property name="basePackage" value="com.songzihao.dao" />
    </bean>

    <!-- 事务配置 -->

</beans>

2.7.3 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.songzihao.controller" />

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

    <!-- 声明springmvc注解驱动 -->
    <mvc:annotation-driven />
</beans>

2.8 编写Java代码(实体类、dao接口和对应的mapper文件、service类、controller类

2.8.1 创建一个实体类 

package com.songzihao.entity;

/**
 *
 */
public class Student {

    private Integer id;
    private String name;
    private Integer age;

    //getter and setter
    //toString
}

2.8.2 创建实体类对应的dao接口和接口对应的mapper文件 

package com.songzihao.dao;

import com.songzihao.entity.Student;

import java.util.List;

/**
 *
 */
public interface StudentDao {

    int insertStudent(Student student);

    List<Student> selectStudent();
}
<?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.songzihao.dao.StudentDao">
    <!-- 使用insert、update、delete、select标签编写sql语句 -->

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

    <select id="selectStudent" resultType="com.songzihao.entity.Student">
        select id,name,age from student2 order by id asc
    </select>
</mapper>

2.8.3 创建dao接口对应的service接口和实现类

package com.songzihao.service;

import com.songzihao.entity.Student;

import java.util.List;

/**
 *
 */
public interface StudentService {

    int addStudent(Student student);

    List<Student> queryStudent();
}
package com.songzihao.service.impl;

import com.songzihao.dao.StudentDao;
import com.songzihao.entity.Student;
import com.songzihao.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 */
@Service
public class StudentServiceImpl implements StudentService {

    /**
     * studentDao是引用类型,其对象是在spring配置文件中创建
     * 引用类型自动注入,这里使用注解 @Autowired 或者 @Resource
     */
    @Autowired
    private StudentDao studentDao;

    @Override
    public int addStudent(Student student) {
        int rows=studentDao.insertStudent(student);
        return rows;
    }

    @Override
    public List<Student> queryStudent() {
        List<Student> list=studentDao.selectStudent();
        return list;
    }
}

2.8.4 创建一个控制器类(接收并处理请求)

package com.songzihao.controller;

import com.songzihao.entity.Student;
import com.songzihao.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(value = "/student")
public class StudentController {

    /**
     *  声明service对象,调用其中的方法
     *  引用类型自动注入,这里使用注解 @Autowired 或者 @Resource
     */
    @Autowired
    private StudentService studentService;

    //添加学生
    @RequestMapping(value = "/addStudent.do")
    public ModelAndView addStudent(Student student) {
        ModelAndView mv=new ModelAndView();

        //调用service,处理业务逻辑方法,把处理结果返回给用户
        int rows=studentService.addStudent(student);
        String msg="";
        if (rows>0) {
            msg="注册成功!!!";
            mv.addObject("msg",student.getName() + "," + student.getAge());
            mv.setViewName("success");
        }else {
            msg="注册失败!!!";
            mv.addObject("msg",msg);
            mv.setViewName("fail");
        }
        return mv;
    }

    //查询学生
    @RequestMapping(value = "/queryStudent.do")
    @ResponseBody
    public List<Student> queryStudent() {
        List<Student> list=studentService.queryStudent();
        return list;
    }
}

2.9 创建视图文件(jsp)

2.9.1 首页(index.jsp)

<%@ 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>SSM</title>
</head>
<body>
    <div align="center">
        <p>SSM整合开发的例子</p>
        <table>
            <tr>
                <td><a href="addStudent.jsp">注册学生</a></td>
                <td><br/></td>
                <td><a href="queryStudent.jsp">查询学生</a></td>
            </tr>
        </table>
    </div>
</body>
</html>

2.9.2 注册学生页面(addStudent.jsp)

<%@ page contentType="text/html;charset=utf-8" language="java" %>
<html>
<head>
    <title>添加学生</title>
</head>
<body>
    <div align="center">
        <p>注册学生</p>
        <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>提交:</td>
                    <td><input type="submit" value="注册"></td>
                </tr>
            </table>
        </form>
    </div>
</body>
</html>

2.9.3 注册成功和失败的页面(success.jsp、fail.jsp)

<%@ page contentType="text/html;charset=utf-8" language="java" %>
<html>
<head>
    <title>$</title>
</head>
<body>
    <h3>结果:${msg}</h3>
</body>
</html>
<%@ page contentType="text/html;charset=utf-8" language="java" %>
<html>
<head>
    <title>$</title>
</head>
<body>
    <h3>结果:${msg}</h3>
</body>
</html>

2.9.4 查询学生页面(queryStudent.jsp)

<%@ 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>
    <script type="text/javascript" src="js/jquery-3.6.0.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#myBtn").on("click",function () {
                $.ajax({
                    url: "student/queryStudent.do",
                    dataType: "json",
                    success: function (resp) {
                        $("#stuinfo").empty();
                        $.each(resp,function (i,n) {
                            $("#stuinfo").append("<tr><td>" + n.id + "</td>" +
                                                 "<td>" + n.name + "</td>" +
                                                 "<td>" + n.age + "</td></tr>");
                        })
                    }
                })
            })
        })
    </script>
</head>
<body>
    <div align="center">
        <p>查询学生 <button id="myBtn">获取学生信息</button></p>
        <table>
            <thead>
                <tr>
                    <td>id</td>
                    <td>姓名</td>
                    <td>年龄</td>
                </tr>
            </thead>
            <tbody id="stuinfo">

            </tbody>
        </table>
    </div>
</body>
</html>

2.10 为项目配置tomcat,启动测试!!!

2.10.1 注册学生的测试结果 

SSM整合——简单的小项目实战[通俗易懂]

SSM整合——简单的小项目实战[通俗易懂]

SSM整合——简单的小项目实战[通俗易懂]

SSM整合——简单的小项目实战[通俗易懂]

SSM整合——简单的小项目实战[通俗易懂]

2.10.2 查询学生的测试结果 

SSM整合——简单的小项目实战[通俗易懂]

SSM整合——简单的小项目实战[通俗易懂]


3.写在结尾!!!

以上就是整个SSM整合开发的详细步骤,在这当中,只是简单的实现了注册学生、查询学生的功能,还有很多的漏洞、功能不足的地方。。。

毕竟我也是初学者,还希望大佬们勿喷!!!(???)        有需要改进、或是哪里写的不太对的地方,也希望大佬可以指出!!!(???)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/140535.html原文链接:https://javaforall.net

(0)
上一篇 2022年5月27日 下午8:20
下一篇 2022年5月27日 下午8:40


相关推荐

  • pytest指定用例_测试用例怎么编写

    pytest指定用例_测试用例怎么编写前言测试用例在设计的时候,我们一般要求不要有先后顺序,用例是可以打乱了执行的,这样才能达到测试的效果.有些同学在写用例的时候,用例写了先后顺序,有先后顺序后,后面还会有新的问题(如:上个用例返回

    2022年7月28日
    4
  • 接口作为形参的问题

    接口作为形参的问题问题 不知道接口作为形参该怎么写例子 接口类 publicinterf publicabstra 接口的操作类调入接口参数 classTestimp publicvoidus Demodemo demo Jump

    2026年3月18日
    3
  • 书单解说Coze工作流:一键生成书本解说,保姆级教程,附提示词

    书单解说Coze工作流:一键生成书本解说,保姆级教程,附提示词

    2026年3月12日
    2
  • Java有哪些编程语言

    Java有哪些编程语言Java作为一种年轻具有活力的编程语言,在最近几年是越来越受到市场的欢迎。它作为面向网络的程序设计语言,用来让程序员创建应用程序。Java是个面向对象的语言,由于它自身具备的入门门槛低等优点。那么,Java编程语言具有什么优点?接下来,就跟着千锋重庆Java的小编一起来了解下吧!1.Java语言是简单的Java语言的语法与C语言和C++语言很接近,使得大多数程序员很容易学习和使用。另一方面,Java丢弃了C++中很少使用的、很难理解的、令人迷惑的那些特性,如操作符重载、多继承、自动的强制类型转换。Jav

    2022年7月7日
    24
  • js在数组指定位置添加元素_java数组删除指定位置元素

    js在数组指定位置添加元素_java数组删除指定位置元素原文链接:Array:InsertanItemataSpecificIndexwithJavaScript原文日期:2014年07月24日翻译日期:2014年07月26日翻译人员:铁锚很多与数组有关的任务听起来很简单,但实际情况并不总是如此,而开发人员在很多时候也用不到他。最近我碰到了这样一个需求:将一个元素插入到现有数组的特定索引处。听起来很容易和常见,但需要一点时间

    2022年8月11日
    7
  • 弹性布局和AndroidAutoSize屏幕适配

    弹性布局和AndroidAutoSize屏幕适配导言:技术在不断的革新,需要有新的技术代替老的方案,老的不再维护,新的一直推荐,作为技术也不能一直停滞不前概念:弹性布局(约束布局):ConstraintLayout可以算是RelativeLayout的升级版屏幕适配:百分比和最小宽度从px的AndroidAutoLayout方案到dp,pm等主副单位AndroidAutoSize方案案例步骤:1:ConstraintLayo…

    2022年6月3日
    42

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号