SSM框架整合教程

前言:


基本概念


SSM:Spring+SpringMVC+MyBatis


Spring

Spring是一个开源框架,Spring是于2003年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。 简单来说,Spring是一个轻量级的控制反转(IOC)和面向切面(AOP)的容器框架。


SpringMVC 

Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring MVC 分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。


MyBatis

MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。MyBatis是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO)MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML或注解用于配置和原始映射,将接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。


SSM框架整合是当下最流行的企业级项目技术选型,三个框架分别负责不同的功能,整合起来共同来支持企业级项目的开发需求,与SSH的思想是一样,只不过替换了更优秀的框架,用SpringMVC替代Struts2,用MyBatis替代Hibernate。


SpringMVC负责MVC设计模式的实现,MyBatis负责数据持久层,Spring的IOC来管理SpringMVC和MyBatis相关对象的创建注入,Spring的AOP负责事务管理。





关于SSM框架整合的理论知识,这里不做过多的赘述了,很多朋友在学习这个流行框架的时候,都希望找到一个最简单的SSM框架搭建方法,今天就教给大家这个方法,不说过多的废话了,直接上手开始搭建。


1.创建Java Web工程,Maven引入依赖jar包。

pom.xml:


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

 <modelVersion>4.0.0</modelVersion>
 <groupId>com.southwind</groupId>
 <artifactId>SSMMaven</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>SSMMaven Maven Webapp</name>
 <url>http://maven.apache.org</url>
 <dependencies>

       <!-- SpringMVC -->
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-webmvc</artifactId>
           <version>4.3.7.RELEASE</version>
       </dependency>

       <!-- Spring JDBC -->
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-jdbc</artifactId>
           <version>4.3.7.RELEASE</version>
       </dependency>

       <!-- Spring AOP -->
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-aspects</artifactId>
           <version>4.3.7.RELEASE</version>
       </dependency>

       <!-- MyBatis -->
       <dependency>
           <groupId>org.mybatis</groupId>
           <artifactId>mybatis</artifactId>
           <version>3.4.2</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.41</version>
       </dependency>

       <!-- C3P0数据源 -->
       <dependency>
           <groupId>c3p0</groupId>
           <artifactId>c3p0</artifactId>
           <version>0.9.1</version>
       </dependency>

       <!-- JSTL -->
       <dependency>
           <groupId>jstl</groupId>
           <artifactId>jstl</artifactId>
           <version>1.2</version>
       </dependency>

       <!-- ServletAPI -->
       <dependency>
           <groupId>javax.servlet</groupId>
           <artifactId>javax.servlet-api</artifactId>
           <version>3.0.1</version>
           <scope>provided</scope>
       </dependency>

 </dependencies>
 <build>
   <finalName>SSMMaven</finalName>
 </build>
</project>


2.web.xml配置开启Spring,SpringMVC,字符编码过滤器,加载静态资源(因为SpringMVC会拦截所有请求,导致JSP页面中对js和css的引用也被拦截,配置后可以把对静态资源(js,css,图片等)的请求交给项目的默认拦截器而不是SpringMVC)。


<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >


<web-app>
 <display-name>Archetype Created Web Application</display-name>

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

 <!-- SpringMVC的前端控制器,拦截所有请求 -->
 <servlet>
   <servlet-name>mvc-dispatcher</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   <init-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>classpath:springmvc.xml</param-value>
   </init-param>
 </servlet>

 <servlet-mapping>
   <servlet-name>mvc-dispatcher</servlet-name>
   <url-pattern>/</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>

 <!-- 加载静态资源 -->
 <servlet-mapping>
     <servlet-name>default</servlet-name>
     <url-pattern>*.js</url-pattern>
 </servlet-mapping>

 <servlet-mapping>
     <servlet-name>default</servlet-name>
     <url-pattern>*.css</url-pattern>
 </servlet-mapping>

</web-app>


3.SSM框架的整合是通过设置各自的配置文件来完成的,配置文件存放在resources目录下。




查看

applicationContext.xml:Spring的配置文件。

dbconfig.properties:数据库配置文件。

mybatis-config.xml:MyBatis的配置文件。

springmvc.xml:SpringMVC的配置文件。


我们知道SpringMVC本就是Spring框架的一个后续产品,所以SpringMVC和Spring不存在整合,所谓的SSM整合实际上是将MyBatis和Spring进行整合,换句话说,让Spring来管理MyBatis。


4.applicationContext.xml配置MyBatis相关信息,以及事务管理。


<?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/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"
>


   <!-- 加载外部文件 -->
   <context:property-placeholder location="classpath:dbconfig.properties"/>
   
   <!-- 配置C3P0数据源 -->
   <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
       <property name="user" value="${jdbc.user}"></property>
       <property name="password" value="${jdbc.password}"></property>
       <property name="driverClass" value="${jdbc.driverClass}"></property>
       <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
       <property name="initialPoolSize" value="5"></property>
       <property name="maxPoolSize" value="10"></property>
   </bean>

   <!-- 配置MyBatis SqlSessionFactory -->
   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
       <!-- 指定MyBatis数据源 -->
       <property name="dataSource" ref="dataSource"/>
       <!-- 指定MyBatis mapper文件的位置 -->
       <property name="mapperLocations" value="classpath:com/southwind/dao/*.xml"/>
       <!-- 指定MyBatis全局配置文件的位置 -->
       <property name="configLocation" value="classpath:mybatis-config.xml"></property>
   </bean>

   <!-- 扫描MyBatis的mapper接口 -->
   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       <!--扫描所有DAO接口的实现,加入到IOC容器中 -->
       <property name="basePackage" value="com.southwind.dao"/>
   </bean>

   <!-- 配置事务管理器 -->
   <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="*"/>
           <!-- 以get开始的所有方法  -->
           <tx:method name="get*" read-only="true"/>
       </tx:attributes>
   </tx:advice>

   <!-- 开启基于注解的事务  -->
   <aop:config>
       <!-- 切入点表达式 -->
       <aop:pointcut expression="execution(* com.southwind.service.impl.*.*(..))" id="txPoint"/>
       <!-- 配置事务增强 -->
       <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
   </aop:config>
</beans>


5.dbconfig.properties配置数据库连接信息。


jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=UTF-8
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root


6.mybatis-config.xml配置MyBatis的相关设置,因为MyBatis的大部分配置交给Spring来管理了,即在applicationContext.xml中进行了配置,所以,mybatis-config.xml只是配置一些辅助性设置,可以省略。


<?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>
       <!-- 打印SQL-->
       <setting name="logImpl" value="STDOUT_LOGGING" />
   </settings>

   <typeAliases>
       <!-- 指定一个包名,MyBatis会在包名下搜索需要的JavaBean-->
       <package name="com.southwind.entity"/>
   </typeAliases>

</configuration>


7.配置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:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"
>


   <!-- 告知spring,启用springmvc的注解驱动 -->
   <mvc:annotation-driven />

   <!-- 扫描业务代码 -->
   <context:component-scan base-package="com.southwind"></context:component-scan>

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

</beans>


8.SSM环境搭建完成,在MySQL中创建数据表department,employee。


DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
 `d_id` int(11) NOT NULL AUTO_INCREMENT,
 `d_name` varchar(255) DEFAULT NULL,
 PRIMARY KEY (`d_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

INSERT INTO `department` VALUES ('1', '研发部');
INSERT INTO `department` VALUES ('2', '销售部');
INSERT INTO `department` VALUES ('3', '行政部');


DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
 `e_id` int(11) NOT NULL AUTO_INCREMENT,
 `e_name` varchar(255) DEFAULT NULL,
 `e_gender` varchar(255) DEFAULT NULL,
 `e_email` varchar(255) DEFAULT NULL,
 `e_tel` varchar(255) DEFAULT NULL,
 `d_id` int(11) DEFAULT NULL,
 PRIMARY KEY (`e_id`),
 KEY `d_id` (`d_id`),
 CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`d_id`) REFERENCES `department` (`d_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

INSERT INTO `employee` VALUES ('1', '张三', '男', 'zhangsan@163.com', '13567896657', '1');
INSERT INTO `employee` VALUES ('2', '李四', '男', 'lisi@163.com', '16789556789', '1');
INSERT INTO `employee` VALUES ('3', '王五', '男', 'wangwu@163.com', '16678906541', '2');
INSERT INTO `employee` VALUES ('4', '小明', '男', 'xiaoming@163.com', '15678956781', '2');
INSERT INTO `employee` VALUES ('5', '小红', '女', 'xiaohong@163.com', '13345678765', '3');
INSERT INTO `employee` VALUES ('6', '小花', '女', 'xiaohua@163.com', '18367654678', '3');


9.创建实体类Department,Employee。


public class Department {
   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;
   }
   public Department(int id, String name) {
       super();
       this.id = id;
       this.name = name;
   }
   public Department() {
       super();
   }

}


public class Employee {
   private int id;
   private String name;
   private String gender;
   private String email;
   private String tel;
   private Department department;
   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;
   }
   public String getGender() {
       return gender;
   }
   public void setGender(String gender) {
       this.gender = gender;
   }
   public String getEmail() {
       return email;
   }
   public void setEmail(String email) {
       this.email = email;
   }
   public String getTel() {
       return tel;
   }
   public void setTel(String tel) {
       this.tel = tel;
   }
   public Department getDepartment() {
       return department;
   }
   public void setDepartment(Department department) {
       this.department = department;
   }


}


10.数据库测试数据创建完成,接下来开始写业务代码,首先Controller。


@Controller
public class EmployeeController {

   @Autowired
   private EmployeeService employeeService;

   /**
    * 查询所有员工
    * @return
    */

   @RequestMapping(value="/queryAll")
   public ModelAndView test(){
       List<Employee> list = employeeService.queryAll();
       ModelAndView modelAndView = new ModelAndView();
       modelAndView.setViewName("index");
       modelAndView.addObject("list", list);
       return modelAndView;
   }

}


11.Controller调用Service,创建Service接口,实现类。


public interface EmployeeService {
   public List<Employee> queryAll();
}


@Service
public class EmployeeServiceImpl implements EmployeeService{

   @Autowired
   private EmployeeDAO employeeDAO;

   public List<Employee> queryAll() {
       // TODO Auto-generated method stub
       return employeeDAO.queryAll();
   }

}


12.Service调用DAO,创建DAO接口,此时没有DAO的实现类。使用MyBatis框架,在DAO.xml中配置实现接口方法需要的SQL,程序运行时,通过动态代理产生实现接口的代理对象。


public interface EmployeeDAO {
   public List<Employee> queryAll();
}


<?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.southwind.dao.EmployeeDAO">

   <resultMap type="Employee" id="employeeMap">
       <id property="id" column="e_id"/>
       <result property="name" column="e_name"/>
       <result property="gender" column="e_gender"/>
       <result property="email" column="e_email"/>
       <result property="tel" column="e_tel"/>
       <association property="department" javaType="Department">
           <id property="id" column="d_id"/>
           <result property="name" column="d_name"/>
       </association>
   </resultMap>

   <select id="queryAll" resultMap="employeeMap">
       select * from employee e, department d where e.d_id = d.d_id
   </select>

</mapper>


13.创建index.jsp,前端使用bootstrap框架。


<%@ page language="java" contentType="text/html; charset=UTF-8"
   pageEncoding="UTF-8"%>
<%@ page isELIgnored="false" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>
<link rel="stylesheet" href="static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
</head>
<body>

   <div class="container">
       <!-- 标题 -->
       <div class="row">
           <div class="col-md-12">
               <h1>SSM-员工管理</h1>
           </div>
       </div>
       <!-- 显示表格数据 -->
       <div class="row">
           <div class="col-md-12">
               <table class="table table-hover" id="emps_table">
                   <thead>
                       <tr>
                           <th>
                               <input type="checkbox" id="check_all"/>
                           </th>
                           <th>编号</th>
                           <th>姓名</th>
                           <th>性别</th>
                           <th>电子邮箱</th>
                           <th>联系电话</th>
                           <th>部门</th>
                           <th>操作</th>
                       </tr>
                   </thead>
                   <tbody>
                       <c:forEach items="${list }" var="employee">
                           <tr>
                               <td><input type='checkbox' class='check_item'/></td>
                               <td>${employee.id }</td>
                               <td>${employee.name }</td>
                               <td>${employee.gender }</td>
                               <td>${employee.email }</td>
                               <td>${employee.tel }</td>
                               <td>${employee.department.name }</td>
                               <td>
                                   <button class="btn btn-primary btn-sm edit_btn">
                                       <span class="glyphicon glyphicon-pencil">编辑</span>
                                   </button>&nbsp;&nbsp;
                                   <button class="btn btn-danger btn-sm delete_btn">
                                       <span class="glyphicon glyphicon-trash">删除</span>
                                   </button>
                               </td>
                           </tr>
                       </c:forEach>
                   </tbody>
               </table>
           </div>
       </div>

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


14.部署tomcat,启动,测试。




SSM框架搭建成功。


注意:

1.Controller,Service,DAO交给IOC容器管理,一定要结合配置文件的自动扫描和类定义处的注解完成,对象之间的依赖注入通过@Autowire来完成。


<!-- 扫描业务代码 -->
<context:component-scan base-package="com.southwind"></context:component-scan>


@Controller
public class EmployeeController {

   @Autowired
   private EmployeeService employeeService;


2.DAO.xml的namspace与DAO接口一定要对应起来,不能写错。


<mapper namespace="com.southwind.dao.EmployeeDAO">


3.DAO.xml中的parameterType和resultType,或者resultMap所对应的类型要与mybatis-config.xml中配置的typeAliases结合使用,组成对应实体类的全类名,如果mybatis-config.xml中没有配置typeAliases,则DAO.xml中直接写实体类的全类名即可。


<resultMap type="Employee" id="employeeMap">


<typeAliases>
   <!-- 指定一个包名,MyBatis会在包名下搜索需要的JavaBean-->
   <package name="com.southwind.entity"/>
</typeAliases>



源码:


百度网盘:

链接: https://pan.baidu.com/s/1rasnMvq 

密码: r928


gitee:

https://gitee.com/southwind9801/SSM

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值