Spring+Sping MVC + Mybatis 三大框架整合详细步骤(SSM)

 

更多内容,点击了解: https://how2j.cn/k/ssm/ssm-tutorial/1137.html?p=81777

本例演示从0开始逐一整合SSM的步骤,要学习本知识,需要具备SpringSpringMVCMybatis 的基础,如果没有这些基础,请把基础掌握之后再学习,不要跳跃学习,欲速则不达。 

必读: 基于框架的程序要成功运行,对于JAR包的版本,配置文件的正确性有着苛刻的要求,任何一个地方出错了,都会导致框架程序运行失败。 如果你是第一次学习本框架,务必严格按照教程的指导,完全模仿操作,直到成功看到运行效果。 第一次成功之后,信心,思路都会有较好的铺垫,然后再根据自己的疑惑,在“成功”的代码上做原本想做的改动和调整,这样可以大大节约学习的时间,提高效率,切勿一来就擅自改动,给自己的学习制造障碍

步骤1:IDEA
步骤2:数据库
步骤3:创建表
步骤4:准备数据
步骤5:JDK版本
步骤6:先运行,再学习
步骤7:新建项目
步骤8:导入jar包
步骤9:pojo
步骤10:CategoryMapper
步骤11:Category.xml
步骤12:CategoryService
步骤13:CategoryServiceImpl
步骤14:CategoryController
步骤15:web.xml
步骤16:applicationContext.xml
步骤17:springMVC.xml
步骤18:listCategory.jsp
步骤19:部署在tomcat中,重启测试
步骤20:思路图
步骤21:删掉,从头开始,这次全部自己做

步骤 1 : IDEA

本教程是使用Eclipse制作的,如果是用IDEA,请跳转到 IDEA 如何创建SSM项目。 但是跳转过去后的教程,没有当前对每个类,配置文件,JSP的讲解有那么详细,所以最好使用Eclipse把当前的教程撸一遍,理解之后,再使用IDEA教程

步骤 2 : 数据库

首先准备数据库 how2java
如果没有安装数据库,请参考 安装mysql-server

注: 新安装的数据库账号密码是root:admin, 后续的配置里,也是用的这个账号密码。如果密码不是这个,本知识点下载区(点击进入)的可运行项目跑不起来,所以尽量修改密码为admin, 修改密码办法:修改root密码

create database how2java;

步骤 3 : 创建表

接着准备表Category只有2个字段id和name

use how2java;

  

CREATE TABLE category_ (

  id int(11) NOT NULL AUTO_INCREMENT,

  name varchar(30) ,

  PRIMARY KEY (id)

) DEFAULT CHARSET=UTF8;

步骤 4 : 准备数据

use how2java;

   

insert into category_ values(null,"category1");

insert into category_ values(null,"category2");

insert into category_ values(null,"category3");

insert into category_ values(null,"category4");

insert into category_ values(null,"category5");

select * from category_

步骤 5 : JDK版本

本教程是通过JDK8编译的,如果您机器上运行环境是低版本JDK,将无法识别其中的类,否则会出现如图所示的错误。 
请使用JDK8 ,请参考 检测JDK版本,以及下载与配置

请勿使用JDK9 或者更高版本,有兼容性风险

JDK版本

步骤 6 : 先运行,再学习

SSM整合需要做不少步骤,任何一步部做漏了,做错了,都有可能失败,这样会影响学习的信心,并且误以为本教程是走不通的。

所以先下载下载区(点击进入)的可运行项目 ssm.rar,解压后导入到eclipse中,启动Tomcat,观察是否正常运行。确定可以运行,确定教程是可以跑得起来的,再学习下面的内容。

导入到Eclipse中并运行的办法请参考:导入动态Web项目到Eclipse中


部署成功之后,测试地址

http://127.0.0.1:8080/ssm/listCategory

先运行,再学习

步骤 7 : 新建项目

在eclipse中新建项目ssm,使用dynamic web project的方式。 不熟悉这种方式的同学,请参考 使用Dynamic Web Project的方式开发J2EE应用

新建项目

步骤 8 : 导入jar包

下载下载区(点击进入)的lib.rar, 解压后复制到 e:/project/ssm/WebContent/WEB-INF/lib目录下

步骤 9 : pojo

package com.how2java.pojo;

public class Category {

    private int id;

    private String name;

    public int getId() {

        return id;

    }

    public void setId(int id) {

        this.id = id;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    @Override

    public String toString() {

        return "Category [id=" + id + ", name=" + name + "]";

    }

     

}

步骤 10 : CategoryMapper

package com.how2java.mapper;

  

import java.util.List;

import com.how2java.pojo.Category;

  

public interface CategoryMapper {

  

    public int add(Category category); 

        

    public void delete(int id); 

        

    public Category get(int id); 

      

    public int update(Category category);  

        

    public List<Category> list();

     

    public int count(); 

     

}

步骤 11 : Category.xml

Category.xml需要和CategoryMapper放在同一个包下面,并且namespace必须写CategoryMapper的完整类名

<?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.how2java.mapper.CategoryMapper">

        <insert id="add" parameterType="Category" >

            insert into category_ ( name ) values (#{name})   

        </insert>

         

        <delete id="delete" parameterType="Category" >

            delete from category_ where id= #{id}  

        </delete>

         

        <select id="get" parameterType="_int" resultType="Category">

            select * from   category_  where id= #{id}   

        </select>

        <update id="update" parameterType="Category" >

            update category_ set name=#{name} where id=#{id}   

        </update>

        <select id="list" resultType="Category">

            select * from   category_     

        </select>    

    </mapper>

步骤 12 : CategoryService

package com.how2java.service;

import java.util.List;

import com.how2java.pojo.Category;

public interface CategoryService {

    List<Category> list();

}

步骤 13 : CategoryServiceImpl

CategoryServiceImpl被注解@Service标示为一个Service
并且装配了categoryMapper

package com.how2java.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import com.how2java.mapper.CategoryMapper;

import com.how2java.pojo.Category;

import com.how2java.service.CategoryService;

@Service

public class CategoryServiceImpl  implements CategoryService{

    @Autowired

    CategoryMapper categoryMapper;

     

    public List<Category> list(){

        return categoryMapper.list();

    }

}

步骤 14 : CategoryController

CategoryController被@Controller标示为了控制器
自动装配了categoryService
通过@RequestMapping映射访问路径/listCategory路径到方法listCategory()。
在listCategory()方法中,通过categoryService获取后,然后存放在"cs"这个key上。

package com.how2java.controller;

import java.util.List;

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;

import com.how2java.pojo.Category;

import com.how2java.service.CategoryService;

// 告诉spring mvc这是一个控制器类

@Controller

@RequestMapping("")

public class CategoryController {

    @Autowired

    CategoryService categoryService;

    @RequestMapping("listCategory")

    public ModelAndView listCategory(){

        ModelAndView mav = new ModelAndView();

        List<Category> cs= categoryService.list();

         

        // 放入转发参数

        mav.addObject("cs", cs);

        // 放入jsp路径

        mav.setViewName("listCategory");

        return mav;

    }

}

步骤 15 : web.xml

在WEB-INF目录下新增加web.xml,这个web.xml有两个作用:
1. 通过ContextLoaderListener在web app启动的时候,获取contextConfigLocation配置文件的文件名applicationContext.xml,并进行Spring相关初始化工作

2. 有任何访问,都被DispatcherServlet所拦截,这就是Spring MVC那套工作机制了。

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

         xmlns="http://java.sun.com/xml/ns/javaee"

         xmlns:web="http://java.sun.com/xml/ns/javaee"

         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">

     

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

     

    <!-- spring mvc核心:分发servlet -->

    <servlet>

        <servlet-name>mvc-dispatcher</servlet-name>

        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <!-- spring mvc的配置文件 -->

        <init-param>

            <param-name>contextConfigLocation</param-name>

            <param-value>classpath:springMVC.xml</param-value>

        </init-param>

        <load-on-startup>1</load-on-startup>

    </servlet>

    <servlet-mapping>

        <servlet-name>mvc-dispatcher</servlet-name>

        <url-pattern>/</url-pattern>

    </servlet-mapping>

     

</web-app>

步骤 16 : applicationContext.xml

在src目录下新建applicationContext.xml文件,这是Spring的配置文件,其作用
1. 通过注解,将Service的生命周期纳入Spring的管理

<context:annotation-config />

<context:component-scan base-package="com.how2java.service" />



2. 配置数据源

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">



3. 扫描存放SQL语句的Category.xml

<bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">



4. 扫描Mapper,并将其生命周期纳入Spring的管理

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

<?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:aop="http://www.springframework.org/schema/aop"

    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"

    xmlns:context="http://www.springframework.org/schema/context"

    xmlns:mvc="http://www.springframework.org/schema/mvc"

    xsi:schemaLocation="

     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd

     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd

     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd

     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

     

   <context:annotation-config />

    <context:component-scan base-package="com.how2java.service" />

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"

      <property name="driverClassName"

          <value>com.mysql.jdbc.Driver</value> 

      </property> 

      <property name="url"

          <value>jdbc:mysql://localhost:3306/how2java?characterEncoding=UTF-8</value> 

     

      </property> 

      <property name="username"

          <value>root</value> 

      </property> 

      <property name="password"

          <value>admin</value> 

      </property>    

    </bean>

     

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">

        <property name="typeAliasesPackage" value="com.how2java.pojo" />

        <property name="dataSource" ref="dataSource"/>

        <property name="mapperLocations" value="classpath:com/how2java/mapper/*.xml"/>

    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

        <property name="basePackage" value="com.how2java.mapper"/>

    </bean>

     

</beans>

步骤 17 : springMVC.xml

在src目录下新建springMVC.xml

1. 扫描Controller,并将其生命周期纳入Spring管理

<context:annotation-config/>

<context:component-scan base-package="com.how2java.controller">

      <context:include-filter type="annotation"

      expression="org.springframework.stereotype.Controller"/>

</context:component-scan>



2. 注解驱动,以使得访问路径与方法的匹配可以通过注解配置

<mvc:annotation-driven />



3. 静态页面,如html,css,js,images可以访问

<mvc:default-servlet-handler />



4. 视图定位到/WEB/INF/jsp 这个目录下

<bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <property name="viewClass"

            value="org.springframework.web.servlet.view.JstlView" />

        <property name="prefix" value="/WEB-INF/jsp/" />

        <property name="suffix" value=".jsp" />

    </bean>

<?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:aop="http://www.springframework.org/schema/aop"

    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"

    xmlns:context="http://www.springframework.org/schema/context"

    xmlns:mvc="http://www.springframework.org/schema/mvc"

    xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd

        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd

        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd

        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <context:annotation-config/>

    <context:component-scan base-package="com.how2java.controller">

          <context:include-filter type="annotation"

          expression="org.springframework.stereotype.Controller"/>

    </context:component-scan>

    <mvc:annotation-driven />

     

    <mvc:default-servlet-handler />

    <!-- 视图定位 -->

    <bean

        class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <property name="viewClass"

            value="org.springframework.web.servlet.view.JstlView" />

        <property name="prefix" value="/WEB-INF/jsp/" />

        <property name="suffix" value=".jsp" />

    </bean>

</beans>

步骤 18 : listCategory.jsp

在WEB-INF下创建jsp目录,并创建文件listCategory.jsp。
在这个jsp文件中,通过forEach标签,遍历CategoryController传递过来的集合数据。

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

    pageEncoding="UTF-8" import="java.util.*"%>

  

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

  

<table align='center' border='1' cellspacing='0'>

    <tr>

        <td>id</td>

        <td>name</td>

    </tr>

    <c:forEach items="${cs}" var="c" varStatus="st">

        <tr>

            <td>${c.id}</td>

            <td>${c.name}</td>

               

        </tr>

    </c:forEach>

</table>

步骤 19 : 部署在tomcat中,重启测试

部署在Tomcat中,重启tomcat,然后访问地址,观察效果

http://127.0.0.1:8080/ssm/listCategory



部署办法请参考 通过Eclipse启动Tomcat-Run On Server

步骤 20 : 思路图

1. 首先浏览器上访问路径 /listCategory
2. tomcat根据web.xml上的配置信息,拦截到了/listCategory,并将其交由DispatcherServlet处理。
3. DispatcherServlet 根据springMVC的配置,将这次请求交由CategoryController类进行处理,所以需要进行这个类的实例化
4. 在实例化CategoryController的时候,注入CategoryServiceImpl。 (自动装配实现了CategoryService接口的的实例,只有CategoryServiceImpl实现了CategoryService接口,所以就会注入CategoryServiceImpl)
5. 在实例化CategoryServiceImpl的时候,又注入CategoryMapper
6. 根据ApplicationContext.xml中的配置信息,将CategoryMapper和Category.xml关联起来了。
7. 这样拿到了实例化好了的CategoryController,并调用 list 方法
8. 在list方法中,访问CategoryService,并获取数据,并把数据放在"cs"上,接着服务端跳转到listCategory.jsp去
9. 最后在listCategory.jsp 中显示数据

思路图

步骤 21 : 删掉,从头开始,这次全部自己做

如果是使用的下载区(点击进入)下载的运行项目执行的,那么这个时候,就该把这个项目删掉,然后从头到尾自己做一遍,把这个知识变成自己的东西。


更多内容,点击了解: https://how2j.cn/k/ssm/ssm-tutorial/1137.html?p=81777

发布了134 篇原创文章 · 获赞 12 · 访问量 5144

猜你喜欢

转载自blog.csdn.net/z1c5809145294zv/article/details/105092691