SSM整合

SSM是java web开发中常用的三大开源框架的组合,分别对应java web开发中的web层(表现层),业务层,持久层。分别是Spring MVC,Spring,Mybatis。

1.环境搭建

1.1 需要导入的jar包

这里写图片描述
需要导入的jar包比较多,也可以使用maven的方式搭建开发环境。

1.2 项目概览

因为需要的配置文件比较多,所以看起来有些凌乱。先看下项目的概览,有个大概的印象。
这里写图片描述
这里所有的配置文件全部放在src根目录下,也可以重新创建一个目录config,放所有的配置文件。

2.概述

SSM整合,主要是Spring和Mybatis之间的整合。Spring是一个大容器,可以帮我们管理对象。Spring需要整合Mybaits数据库连接池,以及事务管理。Dao对象和Mapper也需要交给Spring进行管理。而Spring MVC几乎不用整合,至少在本例中,Spring MVC不需要进行额外的配置。

3. 配置文件

3.1 ApplicationContext.xml

这是Spring的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 加载数据库的配置文件 -->
    <context:property-placeholder location="classpath:db.properties" />

    <!--开启spring的注解扫描  -->
    <context:component-scan base-package="com.mq.*">
        <!-- 不扫描注解为controller的类型 -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <!-- 数据库连接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
    </bean>

    <!-- 整合Sql会话工厂归spring管理 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 指定mybatis核心配置文件 -->
        <property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
        <!-- 指定会话工厂使用的数据源 -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置原生Dao实现      ,注意:class必须指定Dao实现类的全路径名称。在xml中声明id,在代码中用注解声明会报错-->
    <bean id="stuDao" class="com.mq.dao.StudentDaoImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean> 

    <!-- Mapper接口代理实现,在xml中声明id,在代码中用注解声明会报错 -->
    <bean id="stuMapper"  class="org.mybatis.spring.mapper.MapperFactoryBean"> 
        <!-- 配置mapper接口的全路径名称 -->
        <property name="mapperInterface" value="com.mq.mapper.StudentMapper"></property>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> 
    </bean> 


     <!--事务管理 : DataSourceTransactionManager dataSource:引用上面定义的数据源-->
     <bean id="txManager"
         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
         <property name="dataSource" ref="dataSource"></property>
     </bean>

     <!--使用声明式事务 transaction-manager:引用上面定义的事务管理器-->
     <tx:annotation-driven transaction-manager="txManager" />
</beans>

这里将数据库的配置交给了db.properties。
db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/study?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root

log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

在ApplicationContext.xml中加载了数据库,配置了连接池,开启了事务管理,管理mybatis的会话工厂。管理了持久层的Dao类和Mapper接口(原生的Dao类和Mapper接口是实现Mybatis开发的两种方式)。管理mybatis的会话工厂需要mybatis的配置文件:SqlMapConfig.xml。

3.2 SqlMapConfig.xml

这是mybaits的配置文件

<?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.mq.pojo"/>
    </typeAliases>

    <mappers>
        <mapper resource="Student.xml"/>
        <mapper resource="com/mq/mapper/StudentMapper.xml"/>
    </mappers>
</configuration>

SqlMapConfig.xml中有两个sql映射文件。Student.xml采用原生Dao的方式,需要获得SqlSession对象来进行增删改长的操作,而StudentMapper.xml使用mybaits提供的Mapper接口编程方式,不需要SqlSession对象。
Student.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语句时,sql的id前面要带着命名空间-->
<mapper namespace="student">

    <!-- 
    id:sql语句唯一标识,不能重复。
    parameterType:属性指明查询时使用的参数类型
    resultType:属性指明查询返回的结果集类型。resultType="com.mq.pojo.Student"表示返回值是Student类型
    #{}占位符:起到占位作用,如果传入的是基本类型(string,long,double,int,boolean,float等),那么#{}中的变量名称可以随意写,一般和属性名相同。
    java.lang.Integer也可以直接写成int
     -->
    <select id="findStuById" parameterType="java.lang.Integer" resultType="com.mq.pojo.Student">
        select * from students where id=#{id}
    </select>

    <!-- 
    如果返回结果为集合,可以调用selectList方法,这个方法返回的结果就是一个集合,所以映射文件中应该配置成集合泛型的类型
    ${}拼接符:字符串原样拼接,如果传入的参数是基本类型(string,long,double,int,boolean,float等),那么${}中的变量名称必须是value
    注意:拼接符有sql注入的风险,所以慎重使用
     -->

    <select id="findStuByName" parameterType="java.lang.String" resultType="com.mq.pojo.Student">
        select * from students where name like '%${value}%'
    </select>

    <!-- 
    #{}:如果传入的是pojo类型,那么#{}中的变量名称必须是pojo中对应的属性,
    如果要返回数据库自增主键:可以使用select LAST_INSERT_ID()-->

    <insert id="insertStu" parameterType="com.mq.pojo.Student" >
        <!-- 执行 select LAST_INSERT_ID()数据库函数,返回自增的主键
        keyProperty:将返回的主键放入传入参数的Id中保存.
        order:当前函数相对于insert语句的执行顺序,在insert前执行是before,在insert后执行是AFTER
        resultType:id的类型,也就是keyproperties中属性的类型
        -->
        <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
            select LAST_INSERT_ID()
        </selectKey>
        insert into students (name,sex,age,tel) values(#{name},#{sex},#{age},#{tel})
    </insert>

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

    <!--传入的是一个pojo类型,就是一个新的对象  -->
    <update id="updateStuById" parameterType="com.mq.pojo.Student">
        update students set name=#{name} where id=#{id}
    </update>

</mapper>

StudentMapper.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接口代理实现编写规则:
    1. 映射文件中namespace要等于接口的全路径名称
    2. 映射文件中sql语句id要等于接口的方法名称
    3. 映射文件中传入参数类型要等于接口方法的传入参数类型
    4. 映射文件中返回结果集类型要等于接口方法的返回值类型
 -->
<mapper namespace="com.mq.mapper.StudentMapper">
    <select id="findStuById" parameterType="java.lang.Integer" resultType="com.mq.pojo.Student">
        select * from students where id=#{id}
    </select>

    <select id="findStuByName" parameterType="java.lang.String" resultType="com.mq.pojo.Student">
        select * from students where name like '%${value}%'
    </select>

    <!-- 
    #{}:如果传入的是pojo类型,那么#{}中的变量名称必须是pojo中对应的属性,
    如果要返回数据库自增主键:可以使用select LAST_INSERT_ID()-->

    <insert id="insertStu" parameterType="com.mq.pojo.Student" >

        <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
            select LAST_INSERT_ID()
        </selectKey>
        insert into students (name,sex,age,tel) values(#{name},#{sex},#{age},#{tel})
    </insert>

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

    <!--传入的是一个pojo类型,就是一个新的对象  -->
    <update id="updateStuById" parameterType="com.mq.pojo.Student">
        update students set name=#{name} where id=#{id}
    </update>

</mapper>
3.3 springmvc.xml

springmvc.xml是SpringMVC的配置文件之一,不需要改变。

<?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-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">


        <!-- 配置自动扫描的包 -->
        <context:component-scan base-package="com.mq.web"></context:component-scan>

        <!-- 配置视图解析器 如何把handler 方法返回值解析为实际的物理视图 -->
          <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name = "prefix" value="/"></property>
            <property name = "suffix" value = ".jsp"></property>
        </bean>  
</beans>
3.4 web.xml

这里需要注册SpringMVC的servlet以及配置Spring的核心监听器,使项目启动的时候就加载Spring的配置文件,即ApplicationContext.xml配置文件。还需要配置SpringMVC的各种请求类型和post请求的乱码。

<?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">
  <!-- 配置Spring的核心监听器: -->
         <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
         </listener>
         <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:ApplicationContext.xml</param-value>
         </context-param>

  <!-- springmvc前端控制器 -->
  <!--必须 有springmvc.xml配置文件,一般在src目录下 -->
  <servlet>
    <servlet-name>springMvc</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>
    <!-- 在tomcat启动的时候就加载这个servlet -->
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springMvc</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>

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

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

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

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

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

  <!-- 配置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>
</web-app>

4. java代码

4.1 持久层

mybaits的持久层可以使用原生的Dao进行开发,和Hibernate一样。也提供Mapper接口这种编程的方式,
StudentDaoImpl类

/**
 * StudentDaoImpl直接继承SqlSessionDaoSupport,SqlSessionDaoSupport中有一个sqlSessionFactory属性,
 * 因此直接使用getSqlSession便可以获取SqlSession对象。
 * @author Administrator
 *
 */
public class StudentDaoImpl  extends SqlSessionDaoSupport implements StudentDao {
    @Override
    public Student findStuById(int id) {
        //sqlSesion是线程不安全的,所以它的最佳使用范围在方法体内
        SqlSession session = this.getSqlSession();
        Student student = session.selectOne("student.findStuById", id);
        System.out.println(student);
        //整合后会话归spring管理,所以不需要手动关闭.
        //session.close();
        return student;
    }

    @Override
    public void insertStu() {
    SqlSession session = this.getSqlSession();
    Student student=new Student();
    student.setAge(25);
    student.setSex("男");
    student.setTel("8552053");
    student.setName("赵云");

    session.insert("student.insertStu", student);
    //提交事务,整合后,不建议使用session提交事务
    //session.commit();
    System.out.println("id值" + student.getId());
    }
}

使用Dao方式最好继承SqlSessionDaoSupport 类。需要在Spring的xml配置文件中进行注册管理。
StudentMapper接口
public interface StudentMapper {
public Student findStuById(int id);
public List findStuByName(String name);
public void insertStu(Student student);

}
需要注意使用Mapper接口方式时,映射文件必须遵循规范。StudentMapper 接口和StudentMapper .xml在同一个包下。

4.2 业务层
@Service(value="stuService")
public class StudentServiceImpl implements StudentService {
    @Resource(name="stuMapper")
    private StudentMapper studentMapper;//Mapper接口
    @Resource(name="stuDao")
    private StudentDao stuDao;//原声的Dao类

    //根据id从数据库查询记录,使用的Mapper接口的方式
    @Override
    public Student findStuById(int id) {
        Student student=studentMapper.findStuById(id);
        return student;
    }
    //插入数据,使用原生Dao的方式
    @Override
    public void insertStu() {
        stuDao.insertStu();

    }


}

在业务层分别调用了原生的Dao方式和Mapper接口方式。

4.3 表现层
@Controller
@RequestMapping("/haha")
public class MyController {
    @Resource(name="stuService")
    private StudentService stuService;

    /**
     * RequestMapping表示请求路径的匹配
     * @return 返回资源名称,根据springmvc.xml中的配置,如果能找到对应的资源,则跳转到该资源,这里跳转到success.jsp页面
     */
    @RequestMapping("/find")
    public String findStuById(){
         Student stu=stuService.findStuById(1);
         System.out.println(stu);
         return "success";
    }

    @RequestMapping("/insert")
    public String insertStu(){
        stuService.insertStu();
        return "success";
    }
}
4.5 POJO类
public class Student {
    private Integer id;
    private String name;
    private String sex;
    private Integer age;
    private String tel;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getTel() {
        return tel;
    }
    public void setTel(String tel) {
        this.tel = tel;
    }
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", sex=" + sex
                + ", age=" + age + ", tel=" + tel + "]";
    }
}

5.页面

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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="haha/find.action">根据id查找数据</a><br>
<a href="haha/insert.action">插入数据</a><br>
</body>
</html>

success.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>Insert title here</title>
</head>
<body>
<h4>Success Page</h4>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值