ssm(spring+springmvc+mybatis)整合

先简单介绍一下这三个框架:

  • springmvc:属于spring提供的一个web框框,是一个中央调度器(前端控制器),负责接收用户请求,交给对应的处理器处理,响应视图
  • mybatis:做持久化的一个框架,封装了jdbc
  • spring:IOC和AOP
    IOC:体现了一种独立服务的概念,本来有应用程序管理的对象之间的依赖关系,现在交给一个独立的容器管理这就叫做控制反转。spring的IOC是采用DI(依赖注入)方式实现的,不需要主动查找和定位对象。注入方式:setter和构造器(IOC是一种思想,就是把对象之间的依赖关系剥离出去,放到一个单独的服务去管理)
    AOP:面向切面编程,提供了一种声明式的服务能力,(可以提供声明式事务)

ssm的集成原理:
springmvc不需要集成,因为springmvc本来就是spring的一部分,无缝对接;spring和mybatis的集成主要是把连接数据库和事务都交给了spring去管理,直接在配置文件中配置即可。
有了spring以后,controller,service,dao层之间的的调用关系,都是spring中的IOC容器来维护,如果没有spring ,这些调用关系,都需要程序员自己编写代码来维护,直接用专门的服务去管理以后,它们之间的耦合度也降低了,所以现在基本上每个web项目,都会用到spring框架


整合步骤

1)jar包,(spring,mybatis,mysql数据库,spring和mybatis的整合包,log4j的包,dbcp数据库连接池包)
2)web.xml
-初始化参数,指定spring配置文件路径
-spring监听器,在服务器启动阶段该监听器实例会被创建,初始化spring配置文件
该监听器实现了ServletContextListener,在ServletContext对象创建和销毁的时候,监听器方法会被执行
-解决post请求中文乱码问题
-springmvc前段控制器,接收用户请求,交给处理器处理,响应视图

3)spring的配置文件
applicationContext-dao.xml 管理dao层 配置数据源,连接池
applicationContext-transaction.xml 控制事物
applicationContext-service.xml 管理service层
springmvc.xml springmvc的配置
4)其他配置文件
db.properties 数据库中的数据源,体现在配置文件,好管理
log4j.properties 日志的输出策略
mybatis-config.xml 管理mybatis的一个配置文件,主要是mapper文件的管理

工程目录如下:
这里写图片描述

具体代码:

1,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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>smm</display-name>

  <!-- 指定spring配置文件路径 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext-*.xml</param-value>
  </context-param>
  <!-- spring的监听器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- postq请求中文乱码问题 -->
  <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>
  <!-- springmvc前端控制 -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 指定springmvc配置文件的路径  默认是在WEB-INF/[servlet-name]-servlet.xml -->
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/springmvc.xml</param-value>
    </init-param>
    <!-- 服务器启动阶段直接创建该实例,如果不配置,什么请求什么时候调用 -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

  <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>
</web-app>

2,db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=root

3,applicationContext-dao.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"
    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
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- 读取db.properties -->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- 第三方连接池dbcp 配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <!-- 驱动 -->
        <property name="driverClassName" value="${jdbc.driver}" />
        <!-- 地址 -->
        <property name="url" value="${jdbc.url}" />
        <!-- 用户名 -->
        <property name="username" value="${jdbc.username}" />
        <!-- 密码 -->
        <property name="password" value="${jdbc.password}" />
    </bean>
    <!-- sqlSessionFactory 通过sqlSessionFactory创建sqlSession-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 指定数据源 -->
        <property name="dataSource"  ref="dataSource"/>
        <!-- 指定mybatis主配置文件 -->
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
    </bean>
    <!-- mapper扫描器 -->
    <bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 指定sqlSessionFactory 直接为beanName ref改为value-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- mapper文件的包路径 ,多个包用逗号或者分号隔开就行-->
        <property name="basePackage" value="com.ssm.dao" />
    </bean>
</beans>

4,applicationContext-transaction.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"
    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
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- 配置事务控制器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 配置数据源 -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 通知 -->
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
        <!-- 传播行为 -->
        <tx:attributes>
            <tx:method name="insert*" isolation="DEFAULT" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
            <tx:method name="update*" isolation="DEFAULT" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
            <tx:method name="delete*" isolation="DEFAULT" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
            <tx:method name="get*" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <!-- 切入点 -->
    <aop:config>
        <aop:advisor advice-ref="transactionAdvice" pointcut="execution(* com.ssm.service.impl.*.*(..))"/>
    </aop:config>
</beans>

5,applicationContext-service.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"
    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
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop.xsd">
    <bean id="userService" class="com.ssm.service.impl.UserServiceImpl"></bean>
</beans>

6,springmvc.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    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-3.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
    <!-- controller扫描器 -->
    <context:component-scan base-package="com.ssm.controller"></context:component-scan>
    <!-- 注解映射器 -->
    <!-- 注解适配器 -->
    <!-- 注解驱动  这个注解驱动配置以后就不用再配置注解映射器和注解适配器了,因为mvc:annotation-driven默认加载了很多的参数绑定的方法,包括上面两个,
         还有json转换解析器等
     -->
    <mvc:annotation-driven />
    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- jsp的前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <!-- jsp的后缀 -->
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

7,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>
    <!-- 全局setting配置,根据需要添加 -->

    <!-- 配置别名 -->
    <typeAliases>
        <!-- 批量扫描别名 -->
        <package name="com.ssm.pojo"/>
    </typeAliases>

    <!-- 配置mapper
    由于使用spring和mybatis的整合包进行mapper扫描,这里不需要配置了。
    必须遵循:mapper.xml和mapper.java文件同名且在一个目录 
     -->

    <!-- <mappers>

    </mappers> -->

</configuration>

8,log4j.properties

log4j.rootCategory=debug, logfile, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c]%n - <%m>%n

log4j.appender.logfile=org.apache.log4j.RollingFileAppender
#log4j.appender.logfile.File=${portal.root}/WEB-INF/logs/portal_console.log
log4j.appender.logfile.File=Mirrors.log
log4j.appender.logfile.MaxFileSize=1024KB
# Keep three backup files
log4j.appender.logfile.MaxBackupIndex=9
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
#Pattern to output : date priority [category] - <message>line_separator
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - <%m>%n

以上就是全部的配置文件,检验一下是否整合成功,做一个简单的登录功能
新建一张用户表,sql:

 DROP TABLE IF EXISTS `user_t`;

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



    insert  into `user_t`(`id`,`username`,`password`,`address`) values (1,'admin','123456','北京');

dao层代码:

UserDao

public interface UserDao {

    /**
     * 根据用户名和密码获取用户信息
     * @param username
     * @param password
     * @return
     */
    public User getUserInfo(String username,String password);
}

UserDao.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">

<mapper namespace="com.ssm.dao.UserDao">
    <select id="getUserInfo" parameterType="java.lang.String" resultType="com.ssm.pojo.User">
        select * from user_t where username=#{0} and password=#{1}
    </select>
</mapper>

UserService

package com.ssm.service.impl;

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

import com.ssm.dao.UserDao;
import com.ssm.pojo.User;
import com.ssm.service.UserService;

public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public User getUserInfo(String username, String password) {
        User user = this.userDao.getUserInfo(username, password);
        return user;
    }

}

controller

package com.ssm.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

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 com.ssm.pojo.User;
import com.ssm.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    @ResponseBody
    public Object login(String username,String password,HttpServletRequest request){
        Map<String,Object> resultMap = new HashMap<String,Object>();
        try {
            User user = this.userService.getUserInfo(username, password);
            //把用户名和用户地址放到session中
            request.getSession().setAttribute("username",user.getUsername());
            request.getSession().setAttribute("address",user.getAddress());
            resultMap.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("success", false);

        }
        return resultMap;
    }
    @RequestMapping("main")
    public String main(){
        //WEB-INF/jsp/xxx.jsp
        return "main";
    }
}

index.jsp(webRoot/index.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>
<base href="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>ssm整合登录测试</title>
<script type="text/javascript" src="jquery/jquery-1.7.2.min.js"></script>
<script type="text/javascript">

    function login(){
        //发送ajax请求完成认证工作
        $.ajax({
            url:"${pageContext.request.contextPath}/user/login.do",
            type:"post",
            data:{
                "username":$("#username").val(),
                "password":$("#password").val()                
            },
            beforeSend:function(){
                $("#message").text("正在进行登录认证请稍后...");
                return true;
            },
            success:function(jsonObject){
                if(jsonObject.success){
                    window.location.href="${pageContext.request.contextPath}/user/main.do";
                }else{
                    alert("用户名或密码错误");
                }
            }
        });
    }
</script>
</head>
<body>
    <table style="margin: 0 auto; padding: 0;" id="__01" width="1265"
            height="626" border="0" cellpadding="0" cellspacing="0"
            align="center">
            <tr>
                <td colspan="3" width="1265" height="181"></td>
            </tr>
            <tr>
                <td width="315" height="283"></td>
                <td class="dlf_03">
                    <div class="dlk">
                        <table width="100%" border="0" cellpadding="2">
                            <tr>
                                <td width="71" align="right" class="wenzi">用户名:</td>
                                <td colspan="3"><label> <input type="text" 
                                        id="username" name="username" tabindex="1" maxlength='20'
                                        class="ocx_style" />
                                </label></td>
                            </tr>
                            <tr>
                                <td align="right" class="wenzi">密&nbsp;码:</td>
                                <td colspan="3"><label> <input type="password"
                                        id="password" name="password" tabindex="1" maxlength='20'
                                        class="ocx_style" />
                                </label></td>
                            </tr>
                            <tr>
                                <td></td>
                                <td style="padding-top: 10px;"><a style="text-decoration: none;" href="javascript:void(0)"
                                    class="test"> <input type="button" onclick="login();"
                                        style="cursor: pointer;height: 27px; width: 45px;" name="dd" value="登录" />
                                </a></td>
                            </tr>
                        </table>
                    </div>

                </td>
                <td width="314" height="283"></td>
            </tr>
            <tr>
                <td colspan="3" width="1265" height="162"></td>
            </tr>

        </table>
</body>
</html>

main.jsp(/WEB-INF/jsp/main.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>
    <h3>欢迎:<%=request.getSession().getAttribute("address") %>来的<%=request.getSession().getAttribute("username") %> 登录ssm整合测试系统!</h3>

</body>
</html>

这样的话,代码全部就写完了,把项目放到tomcat启动,
访问路径:http://localhost:8080/ssm
登录页面:这里写图片描述

点击登录以后,访问成功页面:
这里写图片描述

至此,ssm已经整合完毕,有任何建议请留言,谢谢!

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值