SSM整合

1 篇文章 0 订阅
1 篇文章 0 订阅

SSM框架就是spring、springMVC、MyBatis三个框架的整合。springMVC负责接收请求处理请求。spring负责业务的操作和管理。mybatis负责对数据的操作。

 

使用:

项目结构图:


1. 首先要导入spring、springmvc和mybatis各自的jar包。再导入log4j的jar包方便看日志信息。


2. spring与mybatis的整合。


2.1、准备一张用户表,表中有四个字段,分别为id、name、password、age。并创建与之对应的实体类。

package cn.otote.pojo;

/**
 * Created by otote Cotter on 2018/10/20.
 */
public class User {
    private Integer id;
    private String name;
    private String password;
    private Integer age;

    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 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 +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                '}';
    }
}


2.2 配置文件放在config文件夹内。现在config文件夹内新建五个配置文件。分别为log4j.properties、applicationContext.xml、springmvc.xml、jdbc.properties、mybatis-config.xml。接着一个个来配置。

在log4j.properties文件里面写上以下内容。用来在控制台查看日志。

### #配置根Logger ###
log4j.rootLogger=debug,stdout  
### 输出到控制台 ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
log4j.appender.stdout.Target=System.out  
### 输出样式 布局模式 :包名.文件名。%p:输出级别,%m:输出代码中指定的消息###
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
log4j.appender.stdout.Encoding=UTF-8
log4j.appender.stdout.layout.ConversionPattern= %d{yyy-MM-dd HH\:mm\:ss} %p %c{0}\:%L - %m%n


2.3 在jdbc.properties属性文件中写入jdbc连接的四个参数。

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatisdemo?useSSL=false&sserverTimezone=UTC
jdbc.user=root
jdbc.password=123456



2.4 spring配置文件的配置。在applicationContext.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/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">

    <!--开启自动扫描 use-default-filters="false"将默认扫描机制关闭。-->
    <context:component-scan base-package="cn.otote" use-default-filters="false">
        <!--扫描Service注解  如果需要扫描其他的直接往下添加就行。-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"></context:include-filter>
    </context:component-scan>

    <!--加载刚才创建的jdbc属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

    <!--配置数据源 这里使用c3p0的-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--读取jdbc属性文件的数据 通过${属性}来读取-->
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!--配置sqlSession工厂 与mybatis整合-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
        <!--加载mybatis核心配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <!--mybatis实体类与表的映射文件路径 *代表加载该目录下的所有映射文件-->
        <property name="mapperLocations" value="classpath:cn/otote/mapper/*.xml"></property>
    </bean>

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

    <!--配置sqlSessionTemplate-->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate" scope="prototype">
        <!--注入sqlSession工厂-->
         <constructor-arg ref="sqlSessionFactory"/>
    </bean>

    <!--事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" isolation="DEFAULT" propagation="REQUIRED" read-only="true"/>
            <tx:method name="select*" isolation="DEFAULT" propagation="REQUIRED" read-only="true"/>
            <tx:method name="insert*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"></tx:method>
            <tx:method name="add*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"></tx:method>
            <tx:method name="update*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"></tx:method>
            <tx:method name="delete*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"></tx:method>
        </tx:attributes>
    </tx:advice>

    <!--AOP切面配置-->
    <aop:config>
        <aop:pointcut id="point1" expression="execution( * cn.otote.service.*.*(..))"></aop:pointcut>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="point1"></aop:advisor>
    </aop:config>

    <!--自动为dao层接口创建代理类  就可以不用实现dao层接口了-->
    <bean id="scannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--dao层的包名-->
        <property name="basePackage" value="cn.otote.dao"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>
</beans>

 

2.5 mybatis配置文件配置。因为数据源什么的都交给spring容器配置了,所以mybatis的配置文件基本就不用配置了 ,这里只配置一个为实体类设置别名的属性。在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>
    <typeAliases>
        <!--为实体类包下的所有实体类设置别名-->
        <package name="cn.otote.pojo"></package>
    </typeAliases>
</configuration>


2.6 dao层接口创建及映射文件配置。创建一个IUserDao接口,接口中提供两个方法,一个查询一个添加。

package cn.otote.dao;

import cn.otote.pojo.User;
import java.util.List;

/**
 * Created by otote Cotter on 2018/10/20.
 */
public interface IUserDao {
    public List<User> getUserList();
    public Integer addUser(User user);
}


配置改接口的映射文件。在cn.otote.mapper包中创建一个IUserMapper.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  IUserDao接口的全类名  -->
<mapper namespace="cn.otote.dao.IUserDao">
    <!--实体类与表映射  type为实体类的类型,因为在mybatis配置文件中设置了别名所以这里直接用user即可-->
    <resultMap id="userMap" type="user">
        <!--property为实体类中的属性名称  column为表中字段名  主键id用id标签  其他的用result标签-->
        <id property="id" column="id"></id>
        <result property="name" column="name"></result>
        <result property="password" column="password"></result>
        <result property="age" column="age"></result>
    </resultMap>

    <!--查询所有用户-->
    <!--id为接口中方法的名称  一一对应  -->
    <select id="getUserList" resultMap="userMap">
        select  * from t_user;
    </select>

    <!--添加用户-->
    <insert id="addUser" useGeneratedKeys="true" keyProperty="id">
        insert into t_user (name,password,age) values (#{name},#{password},#{age});
    </insert>
</mapper>

 

2.7 测试。写一个单元测试,测试spring与mybatis整合的功能正不正常。要在单元测试类添加
@RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "classpath:applicationContext.xml")

这两个注解,否则spring无法自动注入。

package cn.otote.init;

import cn.otote.pojo.User;
import cn.otote.service.IUserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * Created by otote Cotter on 2018/10/20.
 */
@RunWith(value = SpringJUnit4ClassRunner.class)//运行环境
@ContextConfiguration(value = "classpath:applicationContext.xml")//spring核心配置文件的位置
public class InitTest {

    @Autowired//自动注入
    private IUserService userService;

    @Test
    public void testGetUserList(){
        List<User> userList = userService.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
    }
}


运行单元测试,查看运行结果。

可以看到这spring与mybatis的整合就完成了。接下来是与springmvc的整合。

 

3 与springmvc的整合。

3.1 首先在cn.otote.service包下创建一个IUserService接口。并声明两个方法。

/**
 * Created by otote Cotter on 2018/10/20.
 */
public interface IUserService {
    public Integer addUser(User user);
    public List<User> getUserList();
}



3.2 创建一个UserServiceImpl实现IUserService接口的方法。

package cn.otote.service.impl;

import cn.otote.dao.IUserDao;
import cn.otote.pojo.User;
import cn.otote.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by otote Cotter on 2018/10/20.
 */
@Service
public class UserServiceImpl implements IUserService {
    //需要与数据库进行交互  所以注入一个IUserDao  因为已经配置了自动为dao层接口创建代理类 
    // 所以spring会自动帮我们注入代理类
    @Autowired
    private IUserDao userDao;

    @Override
    public Integer addUser(User user) {
        return userDao.addUser(user);
    }

    @Override
    public List<User> getUserList() {
        return userDao.getUserList();
    }
}



3.3 springmvc配置文件的配置。在springmvc.xml文件中写入以下内容:

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

    <!--扫描组件  只扫描controller  需要将use-default-filters关闭 不然springmvc容器会创建一份bean  spring也会创建一份,
    而springmvc创建的bean是不具备事务的,所以将扫描机制关闭只让springmvc创建controller的bean-->
    <context:component-scan base-package="cn.otote" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:include-filter>
    </context:component-scan>

    <!--开启注解驱动  注册常用的bean-->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!--不拦截静态资源 如*.js等  不设置静态资源将被拦截导致失效 如jquery无法使用等-->
    <mvc:default-servlet-handler default-servlet-name="default"></mvc:default-servlet-handler>

    <!--视图解析器 有默认的视图解析器  所以可不配置-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--视图名称-->
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
        <!--前缀-->
        <property name="prefix" value="/"></property>
        <!--后缀-->
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>



3.4 web.xml的配置。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--监听器的属性 spring核心配置文件的位置-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!--监听器  tomcat启动的时候初始化spring容器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--编码过滤器-->
    <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>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>


至此配置ssm的配置基本就已经完成了,接下来就是测试。

 

4.测试

4.1 创建一个控制器。在cn.otote.controller包下创建一个UserController类。并写入以下内容:

/**
 * Created by otote Cotter on 2018/10/20.
 */
@Controller
@RequestMapping(value = "/userController")
public class UserController {

    @Autowired
    private IUserService userService;

    @RequestMapping(value = "/getUserList")
    public String getUserList(ModelMap map){
        List<User> userList = userService.getUserList();
        //将userList添加到request作用域
        map.put("userList", userList);
        //转发到userList界面
        return "userList";
    }

    @RequestMapping(value = "/addUser")
    public String addUser(User user){
        userService.addUser(user);
        //添加完后重新查询所有用户
        return "redirect:/userController/getUserList";
    }
}

 

4.2 创建三个jsp页面。分别为index.jsp、userList.jsp、addUser.jsp内容如下:
index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
    <base href="<%=request.getContextPath()+"/"%>">
  </head>
  <body>
  <a href="userController/getUserList">获取用户列表</a>
  </body>
</html>

 

userList.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <base href="<%=request.getContextPath()+"/"%>">
</head>
<body>
<a href="addUser.jsp">添加用户</a>
<table border="1">
    <tr>
        <td>id</td>
        <td>name</td>
        <td>password</td>
        <td>age</td>
    </tr>
    <c:forEach items="${userList}" var="user">
        <tr>
            <td>${user.id}</td>
            <td>${user.name}</td>
            <td>${user.password}</td>
            <td>${user.age}</td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

 

addUser.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <base href="<%=request.getContextPath()+"/"%>">
</head>
<body>
<form action="userController/addUser" method="post">
    用户名:<input type="text" name="name"/><br>
    密码:<input type="text" name="password"/><br>
    年龄:<input type="text" name="age"/><br>
    <input type="submit" value="添加"/><br>
</form>
</body>
</html>

 

接着启动tomcat运行web项目,进行测试。


至此ssm的整合就结束了。


注意:


配置文件中加载配置文件的路径中的classpath:不能少。在单元测试的时候没用classpath可能会正常运行。但是当项目发布的时候没有加classpath会找不到配置文件。

使用idea需要将config文件夹选中右键>mark directory as>sources root。否则会找不到配置文件。

eclipse创建config文件夹的时候要选source folder。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值