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整合开发的详细步骤,在这当中,只是简单的实现了注册学生、查询学生的功能,还有很多的漏洞、功能不足的地方。。。

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

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

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

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)
blank

相关推荐

  • fastclick.js

    fastclick.js;(function(){‘usestrict’;/***@preserveFastClick:polyfilltoremoveclickdelaysonbrowserswithtouchUIs.**@codingstandardftlabs-jsv2*@copyrightTheFinancia

  • debounce实现 js_聊聊lodash的debounce实现

    debounce实现 js_聊聊lodash的debounce实现本文同步自我的Blog前段时间团队内部搞了一个代码训练营,大家组织在一起实现lodash的throttle和debounce,实现起来觉得并不麻烦,但是最后和官方的一对比,发现功能的实现上还是有差距的,为了寻找我的问题,把官方源码阅读了一遍,本文是我阅读完成后的一篇总结。本文只会列出比较核心部分的代码和注释,如果对全部的源码有兴趣的欢迎直接看我的repo:什么是throttle和debo…

  • 【损失函数系列】softmax loss损失函数详解

    【损失函数系列】softmax loss损失函数详解1.损失函数:损失函数(lossfunction)是用来评测模型的预测值f(x)与真实值Y的相似程度,损失函数越小,就代表模型的鲁棒性越好,损失函数指导模型学习。根据损失函数来做反向传播修改模型参数。机器学习的目的就是学习一组参数,使得预测值与真值无限接近。2.softmaxloss:它是损失函数的一种,是softmax和cross-entropyloss组合而成的损失函数。先看softmax,其函数形式如下:其中zj就是某个神经网络全连…

  • ssm整合RabbitMQ(一)「建议收藏」

    ssm整合RabbitMQ(一)「建议收藏」首先说一下RabbitMQ的配置安装好RabbitMQServer之后访问http://localhost:15672/开始首先在Admintab选项中新建一个vh,这个Name需要在后期的代码配置中用到。之后需要给该VH配置一个权限然后配置交换选择Exchangestab将Exchanges与刚才建立的VH绑定然后命名一个交换名字,这个名字在后期的…

  • pycharm 连接数据库报错[通俗易懂]

    pycharm 连接数据库报错[通俗易懂]pycharm连接数据库报错请问出现下面报错是什么原因呢,数据库已连接,运行后就这样了C:\Users\MACHENIKE\PycharmProjects\untitled9\venv\Scripts\python.exeC:/Users/MACHENIKE/PycharmProjects/untitled11/venv/Online-Bookstore-Management-System-master/v1.0/Book_informationUI.pyTraceback(mostrec.

  • Linux命令 – su命令

    Linux命令 – su命令Linux命令-su命令  su是swithuser的缩写,在Linux中su命令可让用户暂时变更登入的身份,除root外变更时须输入所要变更的用户帐号与密码。1.语法:su[参数][-][用户帐号]2.功能:  变更用户身份,若不指定用户帐号,则预设变更为root。3.参数:-c<指令>或–command=<指令> 执行完指定的指令后,即恢复原来的身份。-f或–fast 适用于csh与tsch,使shell不用去读取启动文件。–l

发表回复

您的电子邮箱地址不会被公开。

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