SSM框架(一)之SSM框架整合(Spring,SpringMVC,MyBatis)

本文详细介绍了如何在Web开发中使用SSM框架(Spring、SpringMVC、MyBatis)进行整合,从实体类、Mapper、Dao、Service、Controller到JSP页面的构建过程,以及如何配置和测试整个框架的整合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、基本概念

最近做一个Web网站,选择了使用SSM框架,SSM框架下的Web程序主要用到了三个技术:

1. Spring:用到了注解和自动装配,就是Spring的两个精髓IOC(反向控制)和 AOP(面向切面编程)。
2. SpringMVC:用到了MVC模型,将逻辑代码放到Controller层处理。
3. MyBatis:用到了与数据库打交道的层面,放在所有的逻辑之后,处理与数据库的CRUD相关的操作。

二、SSM框架下代码完成步骤

  1. 先写实体类Entity,定义对象的属性(可以参照数据库中表的字段来设置,数据库的设计应该在所有编码开始之前)。
  2. 写Mapper.xml(Mybatis),其中定义你的功能,对应要对数据库进行的那些操作,比如 insert、selectAll、selectByKey、delete、update等。
  3. 写Dao.java,将Mapper.xml中的操作按照id映射成Java函数。
  4. 写Service.java,为控制层提供服务,接受控制层的参数,完成相应的功能,并返回给控制层。
  5. 写Controller.java,连接页面请求和服务层,获取页面请求的参数,通过自动装配,映射不同的URL到相应的处理函数,并获取参数,对参数进行处理,之后传给服务层。
  6. 写JSP页面调用,请求哪些参数,需要获取什么数据。

    归纳起来就是:
    DataBase ===> Entity ===> Mapper.xml ===> Dao.java ===> Service.java ===> Controller.java ===> Jsp

    三、SSM整合

    整合后完整的目录结构如下:
    SSM整合后的目录结构

    3.1、引入相关jar包

    将所需的jar包复制粘贴到WebContent\WEB-INF\lib文件夹下面

    3.2、Spring与MyBatis的整合

    所有需要的JAR包都引入以后,首先进行Spring与MyBatis的整合,然后再进行JUnit测试

3.2.1、建立spring-mybatis.xml配置文件

这个文件就是用来完成spring和mybatis的整合的。这里面也没多少行配置,主要的就是自动扫描,自动注入,配置数据库。注释也很详细,大家看看就明白了。
spring-mybatis.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: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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 自动扫描 -->
    <context:component-scan base-package="com.cn.cust">
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
        <context:exclude-filter type="annotation"
            expression="org.springframework.web.bind.annotation.ControllerAdvice" />
    </context:component-scan>

    <!-- 配置数据源, 整合其他框架, 事务等. -->
    <!-- 1. 数据源 : DriverManagerDataSource -->
    <bean id="datasource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/db_test" />
        <property name="username" value="root" />
        <property name="password" value="mysql" />
    </bean>

    <!-- 2. mybatis的SqlSession的工厂: SqlSessionFactoryBean dataSource / typeAliasesPackage -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="datasource" />
        <property name="typeAliasesPackage" value="com.cn.cust.entities" />
        <!-- 自动扫描 mapping.xml 文件 -->
        <property name="mapperLocations" value="classpath:com/cn/cust/mapping/*.xml" />
    </bean>

    <!-- 3. mybatis自动扫描加载Sql映射文件 : MapperScannerConfigurer sqlSessionFactory(已过时,目前使用sqlSessionFactoryBeanName) 
        / basePackage(接口映射文件所在的包) -->   
    <bean id="config" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
        <property name="basePackage" value="com.cn.cust.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

    <!-- 4. 事务管理 : DataSourceTransactionManager -->
    <bean id="manager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="datasource" />
    </bean>

    <!-- 5. 使用声明式事务 -->
    <tx:annotation-driven transaction-manager="manager" />

    <!-- 使用 import 节点导入配置文件 -->
    <!-- <import resource="blog/musicboy90/mudual/*/applicationContext-*.xml" /> -->

</beans>

3.2.2、Log4j的配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration>
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m  (%F:%L) \n" />
        </layout>
    </appender>
    <logger name="java.sql">
        <level value="debug" />
    </logger>
    <logger name="org.apache.ibatis">
        <level value="debug" />
    </logger>
    <root>
        <level value="debug" />
        <appender-ref ref="STDOUT" />
    </root>
</log4j:configuration>

3.2.3、JUnit测试

经过以上步骤(到3.2.2,log4j不配也没影响),我们已经完成了Spring和mybatis的整合,这样我们就可以编写一段测试代码来试试是否成功了。

3.2.3.1、创建测试用表

既然我们需要测试,那么我们就需要建立在数据库中建立一个测试表,这个表建的很简单,SQL语句为:

DROP TABLE IF EXISTS `user_t`;  

CREATE TABLE `user_t` (  
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `user_name` varchar(40) NOT NULL,  
  `password` varchar(255) NOT NULL,  
  `age` int(4) NOT NULL,  
  PRIMARY KEY (`id`)  
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;  

/*Data for the table `user_t` */  

insert  into `user_t`(`id`,`user_name`,`password`,`age`) values (1,'测试','sfasgfaf',24);  
3.2.3.2、根据数据表user_t创建实体类User
package com.cn.cust.entities;

public class User {

    private Integer id;

    private String userName;

    private String password;

    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", userName=" + userName + ", password=" + password + ", age=" + age + "]";
    }
}
3.2.3.3、Mapping层
<?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.cn.cust.dao.IUserDao">

    <resultMap type="User" id="userResult">
        <result column="id" property="id"></result>
        <result column="user_name" property="userName"></result>
        <result column="password" property="password"></result>
        <result column="age" property="age"></result>        
    </resultMap>

    <insert id="save" keyColumn="id" keyProperty="id" useGeneratedKeys="true">
        insert into user_t (user_name, password, age) values (#{user_name}, #{password}, #{age})
    </insert>

    <update id="update" parameterType="user">
        update user_t set user_name = #{user_name}, password = #{password}, age = #{age}
        where id = #{id}
    </update>

    <delete id="delete" parameterType="int">
        delete from user_t where id = #{id}
    </delete>

    <select id="findById" parameterType="int" resultMap="userResult">
        select * from user_t where id = #{id}
    </select>

    <select id="getAll" resultType="User">
        SELECT * FROM user_t
    </select>

</mapper>
3.2.3.4、持久层
package com.cn.cust.dao;

import java.util.ArrayList;

import com.cn.cust.entities.User;

/**
 * 
 * @author HuangMinghao 持久层,数据访问对象
 */
public interface IUserDao { 

    void save(User user);

    void update(User user);

    void delete(int id);

    User findById(int id);

    ArrayList<User> getAll();

}
3.2.3.5、建立Service接口和实现类

IUserService.jave

package com.cn.cust.service;

import com.cn.cust.entities.User;

public interface IUserService { 
    public User getUserById(int userId);
}

UserServiceImpl.java

package com.cn.cust.serviceImpl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.cn.cust.dao.IUserDao;
import com.cn.cust.entities.User;
import com.cn.cust.service.IUserService;



@Service("userService")
public class UserServiceImpl implements IUserService {

    @Resource
    private IUserDao userDao;

    @Override
    public User getUserById(int userId) {       
        return this.userDao.findById(userId);
    }

}
3.2.3.6、建立测试类

测试类在src/test/java中建立, 如果测试成功,表示 Spring 和 Mybatis 已经整合成功了 。输出信息使用的是 Log4j 打印到控制台。

package com.cn.cust.test;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.cn.cust.entities.User;
import com.cn.cust.service.IUserService;

@RunWith(SpringJUnit4ClassRunner.class)     // 表示繼承了 SpringJUnit4ClassRunner 類
@ContextConfiguration("classpath:spring-mybatis.xml")
public class TestUser {

    @Resource   
    private IUserService userService;

    @Test
    public void testGetUserName() {
        User user = userService.getUserById(1);
        System.out.println("成功!!" + user.getUserName());
    }

}

测试结果:
这里写图片描述
这里写图片描述

至此, 完成Spring和mybatis这两大框架的整合 ,下面在继续进行SpringMVC的整合。

3.3、整合SpringMVC

上面已经完成了2大框架的整合,SpringMVC的配置文件单独放,然后在web.xml中配置整合

3.3.1、配置spring-mvc.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.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
    <context:component-scan base-package="com.cn.hnust.controller" />

    <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
    <context:component-scan base-package="com.cn.cust"
        use-default-filters="false">
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
        <context:include-filter type="annotation"
            expression="org.springframework.web.bind.annotation.ControllerAdvice" />
    </context:component-scan>

    <!-- 定义跳转的文件的前后缀 ,视图模式配置 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <mvc:default-servlet-handler />

    <mvc:annotation-driven />

</beans>

3.3.2、配置web.xml文件

这里面对spring-mybatis.xml的引入以及配置的spring-mvc的Servlet就是为了完成SSM整合,之前2框架整合不需要在此处进行任何配置。配置一样有详细注释,不多解释了。
web.xml

<?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"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>Text</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>

    <!-- spring 和  mybatis 的配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-mybatis.xml</param-value>
    </context-param>

    <!-- Spring 监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 防止 Spring 内存溢出监听器 -->
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>

    <!-- Spring MVC servlet -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 编码过滤器 -->
    <filter>
        <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 配置 HiddenHttpMethodFilter : 把 Post 请求转化为 DELETE,PUT请求 -->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

3.3.3、测试
至此已经完成了SSM三大框架的整合了,接下来测试一下,如果成功了,那么恭喜你,如果失败了,继续调试吧, 作为程序员就是不停的与BUG做斗争 !
3.3.3.1、新建jsp页面
showUser.jsp 此页面仅输出一下用户名,完成一个 完整的简单流程 。

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!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>
    ${user.userName}
</body>
</html>

3.3.3.2、建立UserController类

UserController.java 控制器

package com.cn.cust.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cn.cust.entities.User;
import com.cn.cust.service.IUserService;

/**
 * 参数传递,最简单的DEMO
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @RequestMapping("/showUser")
    public String toIndex(HttpServletRequest request,Model model) {
        int userId = Integer.parseInt(request.getParameter("id"));
        User user = this.userService.getUserById(userId);
        model.addAttribute("user",user);
        return "showUser";
    }

}

3.3.3.3、部署项目

输入地址: localhost:8080/ 项目名称 /user/showUser?id=1
这里写图片描述
至此,SSM三大框架的整合就完成了,在此基础上可再添加其他功能。

4、源码下载地址:

http://download.youkuaiyun.com/detail/xiaoxiaoxiaohaozi/9405980

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值