百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

SSM(Spring + SpringMVC + Mybatis)的搭建与整合流程

ccwgpt 2024-10-29 13:31 31 浏览 0 评论

最近有粉丝给我留言SSM框架三件套,很重要!自己必须要会,但是不知道该怎么做,所以今天小编给大家整理一个SSM框架的搭建与整合教程案列

在写代码之前我们先了解一下这三个框架分别是干什么的?

  1. SpringMVC:它用于web层,相当于controller(等价于传统的servlet和struts的action),用来处理用户请求。举个例子,用户在地址栏输入http://网站域名/login,那么springmvc就会拦截到这个请求,并且调用controller层中相应的方法,(中间可能包含验证用户名和密码的业务逻辑,以及查询数据库操作,但这些都不是springmvc的职责),最终把结果返回给用户,并且返回相应的页面(当然也可以只返回json/xml等格式数据)。springmvc就是做前面和后面过程的活,与用户打交道!
  2. Spring:太强大了,以至于我无法用一个词或一句话来概括它。但与我们平时开发接触最多的估计就是IOC容器,它可以装载bean(也就是我们java中的类,当然也包括service dao里面的),有了这个机制,我们就不用在每次使用这个类的时候为它初始化,很少看到关键字new。另外spring的aop,事务管理等等都是我们经常用到的。
  3. MyBatis:如果你问我它跟鼎鼎大名的Hibernate有什么区别?我只想说,他更符合我的需求。第一,它能自由控制sql,这会让有数据库经验的人编写的代码时能提升数据库访问的效率。第二,它可以使用xml的方式来组织管理我们的sql,因为一般程序出错很多情况下是sql出错,别人接手代码后能快速找到出错地方,甚至可以优化原来写的sql。


SSM框架整合配置

开发环境

IDE: Eclipse



Jdk: 1.7

数据库: MySQL

注:本例演示采用的开发工具是Eclipse,不要让开发工具限制了你的学习,按照自己的需要来创建就好,用什么工具就按照什么步骤来创建。


项目需求

客户列表查询
根据客户姓名模糊查询

整合思路

第一步:整合dao层

Mybatis和spring整合,通过spring管理mapper接口,使用mapper扫描器自动扫描mapper接口,并在spring中进行注册。

第二步:整合service层

通过spring管理service层,service调用mapper接口。使用配置方式将service接口配置在spring配置文件中,并且进行事务控制。

第三步:整合springMVC

由于springMVC是spring的模块,不需要整合。

我用的是mysql5.7版本,开发工具是ecplise


加入配置文件

mybatis——mybatis配置

spring——spring+springmvc+spring和mybatis配置

jdbc.properties——数据库配置文件

log4j.properties——log日志等


spring的jar包



spring与mybatis的整合jar包


mybatis的jar包


数据库驱动包


log4j包

log4j配置文件


### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n 

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:\mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n


### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=debug, stdout

数据库连接池包



jstl包


整合dao

sqlMapconfig.xml

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>
   <!-- 定义别名 -->
   <typeAliases>
      <package name="com.haohan.ssm.po" />
   </typeAliases>
   <!-- 配置mapper映射文件 -->
   <mappers>
      <!-- 加载 原始dao使用映射文件 -->
      <!-- <mapper resource="sqlmap/User.xml" /> --     
      <!--批量mapper扫描 遵循规则:将mapper.xml和mapper.java文件放在一个目录 且文件名相同 ,现在由spring配置扫描-->
      <!-- <package name="cn.itcast.ssm.dao.mapper" /> -->
   </mappers>
</configuration>

db.properties数据库配置文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/haohan1?characterEncoding=utf8&useSSL=false
jdbc.username=root
jdbc.password=123456

applicationContext-dao.xml

spring在这个xml文件中配置dbcp连接池,sqlSessionFactory,mapper的批量扫描。

<?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:aop="http://www.springframework.org/schema/aop"
   xmlns:tx="http://www.springframework.org/schema/tx"   
  xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop.xsd
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx.xsd">
   <!--1. 数据源 -->
   <!-- 加载配置文件 -->
   <context:property-placeholder location="classpath:db.properties"/>
   <!-- 配置dbcp连接池 -->
      <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
      destroy-method="close">
      <property name="driverClassName" value="${jdbc.driver}"></property>  
      <property name="url" value="${jdbc.url}"></property>
      <property name="username" value="${jdbc.name}"></property>
      <property name="password" value="${jdbc.password}"</property>
      </bean>
     <!--2. sqlSessionFactory -->
   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml"></property>
      <property name="dataSource" ref="dataSource"></property>
   </bean>
   <!-- 3. mapper的批量扫描-->
   <!-- mapper的批量扫描 :从mapper包中扫描mapper接口,自动创建代理对象并且在spring容器中注册。
   遵循的规范:需要将mapper的接口类名和mapper.xml映射文件名保持一致,且在一个目录中。
   自动扫描出来的mapper的bean的id为mapper类名(首字母小写)
   -->
   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
      <!-- 指定扫描的包名
      如果扫描多个包,用半角逗号分开
      -->
      <property name="basePackage" value="cn.haohan.ssm.mapper"></property>
      <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
   </bean>
</beans>

生成po类和mapper接口和mapper.xml文件

生成如下图的文件:



自定义mapper接口和xml文件,以及po的包装类



CustomMapper.java

public interface CustomMapper {
   public List<HhCustom> findAllCustom(HhCustomVo hhCustomVo)throws Exception;
}

CustomMapper.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">
<!-- namespace:命名空间,作用是对sql进行分类化管理,sql隔离 -->
<mapper namespace="cn.haohan.ssm.mapper.CustomMapper">
   <sql id="query_custom_where">
       <if test="hhCustom!=null">
       <if test="hhCustom.name!=null and hhCustom.name!=''">
          name like '%${hhCustom.name}%'
       </if>
       </if>
   </sql>
   <resultMap type="hhCustom" id="hhCustomResultMap">
   <id column="id" property="id"/>
   <result column="phone_number" property="phoneNumber"/>
   </resultMap>
   <select id="findAllCustom" parameterType="cn.haohan.ssm.po.HhCustomVo" resultMap="hhCustomResultMap">
      SELECT
      * FROM hh_custom
       <where>
         <include refid="query_custom_where"></include>
      </where>
   </select>
</mapper>

HhCustomVo

//客户的包装类
public class HhCustomVo {
   //客户信息
   private HhCustom hhCustom;
   public HhCustom getHhCustom() {
      return hhCustom;
   }
   public void setHhCustom(HhCustom hhCustom) {

      this.hhCustom = hhCustom;
   }
}

数据库表结构



整合service

定义service接口

public interface CustomService {
   public HhCustom findCustomById(Integer id)throws Exception;
   public List<HhCustom> findAllCustom(HhCustomVo hhCustomVo)throws Exception;
}

service接口实现

public class CustomServiceImpl implements CustomService{

   @Autowired
   HhCustomMapper hhCustomMapper;
   @Autowired
   CustomMapper customMapper;
   @Override
   public HhCustom findCustomById(Integer id) throws Exception {
      // TODO Auto-generated method stub
      return hhCustomMapper.selectByPrimaryKey(id);
   }
   @Override
   public List<HhCustom> findAllCustom(HhCustomVo hhCustomVo) throws Exception {
      // TODO Auto-generated method stub
      return customMapper.findAllCustom(hhCustomVo);
   }
}

在spring容器配置service(applicationContext-service)

<?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:aop="http://www.springframework.org/schema/aop"
   xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop.xsd
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx.xsd">
   <bean id="CustomServiceImpl" class="cn.haohan.ssm.service.impl.CustomServiceImpl"></bean>
</beans>

事务控制(applicationContext-transaction)

<?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:aop="http://www.springframework.org/schema/aop"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop.xsd
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx.xsd">
   <!-- 配置事务管理器
   对mybatis操作数据库事务控制,spring使用jdbc事务控制类-->
   <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <!-- 配置数据源 -->
      <property name="dataSource" ref="dataSource"></property>
   </bean>
   <!-- 配置事务增强(通知) -->
      <tx:advice id="txadvice" transaction-manager="transactionManager">
      <tx:attributes>
          <!-- 设置进行事务操作的方法匹配规则 -->
          <tx:method name="save*" propagation="REQUIRED"/>
          <tx:method name="update*" propagation="REQUIRED"/>
          <tx:method name="insert*" propagation="REQUIRED"/>
          <tx:method name="delete*" propagation="REQUIRED"/>
          <tx:method name="find*" propagation="SUPPORTS"/>
          <tx:method name="get*" propagation="SUPPORTS"/>
          <tx:method name="select*" propagation="SUPPORTS"/>
      </tx:attributes>
      </tx:advice>
     <!-- aop操作 -->
     <aop:config>
       <aop:advisor advice-ref="txadvice" pointcut="execution(* cn.haohan.ssm.serivce.impl.*.*(..))"/>
     </aop:config>
</beans> 

整合springMVC

springmvc.xml

在springmvc.xml中配置适配器映射器、适配器处理器、视图解析器

<?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:aop="http://www.springframework.org/schema/aop"
   xmlns:tx="http://www.springframework.org/schema/tx"
   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
   http://www.springframework.org/schema/context/spring-context.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop.xsd
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx.xsd
   http://www.springframework.org/schema/mvc
   http://www.springframework.org/schema/mvc/spring-mvc.xsd">
   <!-- 扫描加载handler -->
   <context:component-scan base-package="cn.haohan.ssm.controller"></context:component-scan>
 <!-- 注解映射器 -->
   <!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>
   注解适配器
   <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean> -->
   <!-- 使用mvc:annotation-driven可代替上面的注解映射器和注解适配器mvc:annotation-driven默认加载许多参数绑定,比如json转换解析器,实际开发用mvc:annotation-driven-->
   <mvc:annotation-driven> 
   </mvc:annotation-driven>
 
   <!-- 视图解析器
   解析jsp,默认使用jstl标签,-->
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/jsp/"></property>
      <property name="suffix" value=".jsp"></property>
   </bean>
</beans>

配置前端控制器(web.xml)

<!-- 配置springmvc前端控制器 -->
 <servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
  <!-- contextConfigLocation:加载springmvc的配置文件(配置处理器适配器、映射器、视图解析器
      默认加载的是/WEB-INF/servlet名称-servlet.xml( springmvc-servlet.xml)
  -->
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/springmvc.xml</param-value>
  </init-param>
  </servlet>
  <servlet-mapping>
  <!--第一种:*.action ,访问以.action结尾的,由DispatcherServlet解析。
      第二种:/ ,所有访问的地址都由DispatcherServlet解析,对于静态文件需要配置不让DispatcherServlet解析。
     可以实现Restful风格。
     -->
  <servlet-name>springmvc</servlet-name>
  <url-pattern>*.action</url-pattern>
  </servlet-mapping>

编写controller

@Controller
public class CustomController {

   @Autowired
   CustomService customService;
  
 //模糊查询客户
   @RequestMapping("/findAllCustom")
   public ModelAndView findAllCustom(HhCustomVo hhCustomVo) throws Exception {
      List<HhCustom> customlist = customService.findAllCustom(hhCustomVo);
      ModelAndView modelAndView = new ModelAndView();
      modelAndView.addObject("customlist", customlist);
      modelAndView.setViewName("customlist");
      return modelAndView;
   }

   //根据客户id查询
      public ModelAndView findCustomByid(Integer id) throws Exception {
         HhCustom hhCustom = customService.findCustomById(id);
         ModelAndView modelAndView = new ModelAndView();
         modelAndView.addObject("hhCustom", hhCustom);
         modelAndView.setViewName("customlist");
         return modelAndView;
      }
}


编写jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
   pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>客戶列表</title>
</head>
<body>
   <form name="customForm"
  action="${pageContext.request.contextPath}/findAllCustom.action"
      method="post">
      查询条件:
      <table width="100%" border=1>
         <tr>
            <td>客戶名称:<input name="hhCustom.name" />
            </td>
            <%-- <td>客戶类型: <select name="customType">
                   <c:forEach items="${customType}" var="customType">
                      <option value="${customType.key }">${customType.value}</option>
                   </c:forEach>
            </select>
            </td> --%>
            <td><button type="submit" value="查询" >查询</button></td>
         </tr>
      </table>
      客戶列表:
      <table width="100%" border=1>
         <tr>
            <th>选择</th>
            <th>客戶名称</th>
            <th>客戶邮箱</th>
            <th>客戶电话</th>
            <th>客户类型</th>
           <!-- <th>操作</th> -->
         </tr>
         <c:forEach items="${customlist}" var="custom">
            <tr>
                <td><input type="checkbox" name="custom_id" value="${custom.id}" /></td>
                <td>${custom.name }</td>
                <td>${custom.mail }</td>
                <td>${custom.phoneNumber }</td>
                <td>${custom.category }</td>
                <%--<td><fmt:formatDate value="${custom.birthday }" pattern="yyyy-MM-dd HH:mm:ss"/></td>
    <td><a href="${pageContext.request.contextPath }/items/editItems.action?id=${item.id }">修改</a></td> --%>
            </tr>
        </c:forEach>
      </table>
   </form>
</body>
</html>


加载spring容器(web.xml)

<!-- 加载spring容器 -->
  <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:spring/applicationContext-*.xml</param-value>
  </context-param>
  <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>


Post方法中文乱码(web.xml)

<!-- post中文乱码 -->
  <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>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

最后,开发这么多年我也总结了一套学习Java的资料与面试题,私信我发给你,另外如果你在技术上面想提升自己的话,可以关注我后面更新的内容,有时间记得帮我点下转发让更多的人看到哦。


相关推荐

Java七大热门技术框架源码解析(25章) 完结

获课》aixuetang.xyz/5699/Hibernate与MyBatis源码级PK:ORM框架的两种哲学在Java持久层框架领域,Hibernate与MyBatis代表了两种截然不同的设计哲学。...

【25章】Java七大热门技术框架源码解析

获课》aixuetang.xyz/5699/Java高级面试:七大框架源码精讲与实战解析在当今Java技术生态中,对主流框架源码的深入理解已成为高级开发者面试的核心竞争力。掌握Spring、MyBat...

饿了么董事长吴泽明兼任CEO,韩鎏分管即时物流中心

饿了么调整组织架构。2月11日,饿了么董事长吴泽明(花名:范禹)通过公司全员信宣布饿了么最新组织调整:即日起,吴泽明将兼任饿了么CEO,韩鎏(花名:昊宸)专注分管即时物流中心,继续向吴泽明汇报。吴泽明...

饿了么100%迁至阿里云,快速扩容可支持1亿人同时点单

来源:环球网6月17日,记者获悉,饿了么已完成100%上云,所有业务系统、数据库设施等均已迁移至阿里云。高峰期,饿了么可在阿里云上快速扩容,可以支持1亿人同时在线点单,这意味着饿了么的服务能力再次全面...

饿了么组织架构调整:董事长吴泽明兼任CEO 韩鎏专注即时物流中心管理

近日,饿了么董事长吴泽明(花名:范禹)通过公司全员信宣布饿了么最新组织调整:即日起,吴泽明将兼任饿了么CEO,韩鎏(花名:昊宸)专注分管即时物流中心,继续向吴泽明汇报。吴泽明在内部信中表示,考虑即时物...

饿了么组织架构调整:董事长吴泽明兼任CEO

Tech星球2月11日消息,据新浪科技报道,今日饿了么董事长吴泽明(花名:范禹)通过公司全员信宣布饿了么最新组织调整:即日起,吴泽明将兼任饿了么CEO,韩鎏(花名:昊宸)专注分管即时物流中心,继续向吴...

饿了么又调整了组织架构,董事长吴泽明兼任CEO

2月11日,饿了么董事长,花名为范禹的吴泽明,通过公司全员信宣布最新组织调整:从即日起,吴泽明将兼任饿了么CEO。公司原CEO,花名为昊宸的韩鎏今后专注分管即时物流中心,继续向吴泽明汇报。在内部信中,...

SpringBoot项目快速开发框架JeecgBoot——Web处理!

Web处理JeecgBoot框架主要用于Web开发领域。下面介绍JeecgBoot在Web开发中的常用功能,如控制器、登录、系统菜单、权限模块的角色管理和用户管理。首先启动后台项目,将其导入IDE...

腾讯即将开源Kuikly:基于Kotlin的纯原生跨端解决方案

IT之家3月4日消息,腾讯日前在端服务网站发布预告,即将开源Kuikly跨端开发框架。预告海报介绍称,Kuikly是基于KotlinKMM技术、客户端开发友好的全新跨端解决方案,可...

Python构建MCP服务器完整教程:5步打造专属AI工具调用系统

模型控制协议(ModelControlProtocol,MCP)是一种专为实现AI代理与工具解耦而设计的通信协议,为AI驱动应用程序的开发提供了高度的灵活性和模块化架构。通过MCP服务器,AI代...

Python3使用diagrams生成架构图(python模块制作)

目录技术背景diagrams的安装基础逻辑关系图组件簇的定义总结概要参考链接技术背景对于一个架构师或者任何一个软件工程师而言,绘制架构图都是一个比较值得学习的技能。这就像我们学习的时候整理的一些Xmi...

Python 失宠!Hugging Face 用 Rust 新写了一个 ML框架,现已低调开源

大数据文摘受权转载自AI前线整理|褚杏娟近期,HuggingFace低调开源了一个重磅ML框架:Candle。Candle一改机器学习惯用Python的做法,而是Rust编写,重...

Python Web 框架(Python Web 框架)

Tornado、Flask、Django三个PythonWeb框架的主要区别和适用场景:特点/框架TornadoFlaskDjango类型异步非阻塞Web服务器和框架轻量级微框架全功能...

构建并发布你的自定义 Python 包(python如何创建自定义模块)

Python让你可以重用代码,并将代码分享给他人以节省时间和精力。所以,当你编写了一些方便的脚本,希望你的同事或其他人也能使用时,接下来该怎么做呢?这篇文章就来解决打包和分发的问题。我们将专注于将你...

Python 应用开发框架 BeeWare 简明实用教程

1.BeeWare简介BeeWare是一个Python框架,用于开发跨平台原生应用。它支持Android、iOS、Windows、macOS和Linux,并提供原生用户体验。2.安装B...

取消回复欢迎 发表评论: