你的位置:首页 > Java教程

[Java教程]SSM整合(Spring+Spring MVC +Mybatis)


最近一直在学习Spring相关,于是乎就想整合下SSM,原以为整合的过程是相当的顺利,结果并不是那么的顺利,搜了很多资料,最后还是大Google帮忙了,好了,废话不多说了,开始整合:

1、Maven创建Web项目

2、结构如下,其中的dao、mapping、pojo包中的类、接口、配置文件可以用mabatis generator自动生成;controller包可以先不管,

pom.

<project ="http://maven.apache.org/POM/4.0.0" ="http://www.w3.org/2001/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>cn.spring</groupId><artifactId>spring</artifactId><packaging>war</packaging><version>1.0-SNAPSHOT</version><name>spring Maven Webapp</name><url>http://maven.apache.org</url><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>3.2.15.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>3.2.15.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>3.2.15.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>3.2.15.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId><version>3.2.15.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-expression</artifactId><version>3.2.15.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>3.2.15.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>3.2.15.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-dao</artifactId><version>2.0.8</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>3.2.15.RELEASE</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.16</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.2.1</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.2.3</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version></dependency><dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>1.2</version></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.4</version></dependency><!-- 导入dbcp的jar包,用来在applicationContext.--><dependency><groupId>commons-dbcp</groupId><artifactId>commons-dbcp</artifactId><version>1.2.2</version></dependency><!-- 格式化对象,方便输出日志 --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.1.41</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.13</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.13</version></dependency><!-- 映入JSON --><dependency><groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.9.13</version></dependency></dependencies><build><finalName>spring</finalName><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>1.6</source><target>1.6</target></configuration></plugin></plugins><resources><resource><directory>src/main/java</directory><includes><include>**/*.</include></includes><!-- 是否替换资源中的属性--><filtering>false</filtering></resource></resources></build></project>

最后的resources得说下,之前一直没在pom.

3、Spring与Mabatis整合

所有的jar包都导入后,就可以开始spring和mybatis整合了,配置文件如下图的红色框部分

3.1、建立jdbc属性文件

dbssm.properties本人用的sqlserver

jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriverjdbc.url=jdbc:sqlserver://localhost:1433;DatabaseName=modeljdbc.username=sajdbc.password=starlin.cn#定义初始连接数initialSize=0#定义最大连接数maxActive=20#定义最大空闲maxIdle=20#定义最小空闲minIdle=1#定义最长等待时间maxWait=60000

3.2 建立spring-mybatis.

    这个文件不用多说吧

spring-mybatis.

<??><beans ="http://www.springframework.org/schema/beans"    ="http://www.w3.org/2001/ ="http://www.springframework.org/schema/tx"    ="http://www.springframework.org/schema/aop"    ="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://www.springframework.org/schema/beans            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd            http://www.springframework.org/schema/tx            http://www.springframework.org/schema/tx/spring-tx-3.1.xsd            http://www.springframework.org/schema/aop            http://www.springframework.org/schema/aop/spring-aop-3.1.xsd            http://www.springframework.org/schema/context            http://www.springframework.org/schema/context/spring-context.xsd"><!-- 自动扫描 -->  <context:component-scan base-package="cn" />  <!-- 引入配置文件 -->  <bean id="propertyConfigurer"     class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">    <property name="location" value="classpath:ssm/dbssm.properties" />  </bean>  <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="initialSize" value="${initialSize}"></property>    <!-- 连接池最大数量 -->    <property name="maxActive" value="${maxActive}"></property>    <!-- 连接池最大空闲 -->    <property name="maxIdle" value="${maxIdle}"></property>    <!-- 连接池最小空闲 -->    <property name="minIdle" value="${minIdle}"></property>    <!-- 获取连接最大等待时间 -->    <property name="maxWait" value="${maxWait}"></property>  </bean>  <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">    <property name="dataSource" ref="dataSource" />    <!-- 自动扫描mapping.-->    <property name="mapperLocations" value="classpath:cn/mapping/*.></property>  </bean>  <!-- DAO接口所在包名,Spring会自动查找其下的类 -->  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">    <property name="basePackage" value="cn.dao" />    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  </bean>  <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->  <bean id="transactionManager"     class="org.springframework.jdbc.datasource.DataSourceTransactionManager">    <property name="dataSource" ref="dataSource" />  </bean></beans>

3.3、log4j的配置

Log4j.properties配置很简单

# Global logging configurationlog4j.rootLogger=DEBUG, stdout# MyBatis logging configuration...log4j.logger.mybatis.mybatisDemo=TRACE# Console output...log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n#文件大小到达指定尺寸的时候产生一个新的文件log4j.appender.File = org.apache.log4j.RollingFileAppender#指定输出目录log4j.appender.File.File = logs/ssm.log#定义文件最大大小log4j.appender.File.MaxFileSize = 10MB# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志log4j.appender.File.Threshold = ALLlog4j.appender.File.layout = org.apache.log4j.PatternLayoutlog4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n

3.4、junit测试

经过上面的配置,基本就已完成了spring和mybaits的配置了,就可以写测试类了

当然是写service和serviceImpl实现类

IEmpService.java

ppackage cn.service;import cn.pojo.Emp;public interface IEmpService {  public Emp findById(String id) ;}

EmpServiceImpl.java				
package cn.service.impl;import cn.dao.EmpDao;import cn.pojo.Emp;import cn.service.IEmpService;import org.springframework.stereotype.Service;import javax.annotation.Resource;@Service("userService")public class EmpServiceImpl implements IEmpService {  @Resource()  private EmpDao empDao;  @Override  public Emp findById(String id) {    return empDao.findById(id);  }}

测试类TestMyBatis

package test.mybatis;import cn.pojo.Emp;import cn.service.IEmpService;import com.alibaba.fastjson.JSON;import org.apache.log4j.Logger;import org.junit.Before;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathimport org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import javax.annotation.Resource;@RunWith(SpringJUnit4ClassRunner.class) //表示继承了SpringJUnit4ClassRunner类@ContextConfiguration(locations = {"classpath:ssm/spring-mybatis.})public class TestMyBatis {  private static Logger logger = Logger.getLogger(TestMyBatis.class);  private ApplicationContext applicationContext = null;  @Resource  private IEmpService iEmpService;  @Before  public void before(){    applicationContext = new ClassPathpublic void test(){    Emp user = iEmpService.findById("8888");    logger.info(JSON.toJSONString(user));  }}

    如果测试一直不通过的,请看我前面的说明检查resources,鄙人就是在那里卡了很久了,测试一直无法通过,耽误了很多时间.

测试结果:

  1. 整合SpringMVC

    上面的整合完成了,基本上就是完成了一大步了,整合springmvc就很简单了

4.1、配置spring-mvc.

Spring-mvc.

<??><beans ="http://www.springframework.org/schema/beans"    ="http://www.w3.org/2001/    ="http://www.springframework.org/schema/context"    ="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-3.2.xsd    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"><!--配置Handler-->  <!--视图解析器,因为是使用的jsp,所以要配置jsp的视图解析器-->  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>    <property name="prefix" value="/WEB-INF/springmvc/"/> <!--前缀-->    <property name="suffix" value=".jsp"/><!--后缀-->  </bean>  <!--注解的适配器-->  <!--<bean ></bean>-->  <!--&lt;!&ndash;注解的映射器&ndash;&gt;-->  <!--<bean ></bean>-->  <!--使用mvc的注解驱动代替上面的注解适配器和映射器,实际开发使用此种方式-->  <mvc:annotation-driven></mvc:annotation-driven>  <!--对于注解的handle可以单个配置,实际开发中使用组件扫描-->  <context:component-scan base-package="cn"></context:component-scan>  <!--避免IE执行AJAX时,返回JSON出现下载文件 -->  <bean id="mappingJacksonHttpMessageConverter"     class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">    <property name="supportedMediaTypes">      <list>        <value>text/html;charset=UTF-8</value>      </list>    </property>  </bean>  <!--文件上传设定,需要导入相关的包commons-fileupload、commons-io-->  <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->  <bean id="multipartResolver"     class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    <!-- 默认编码 -->    <property name="defaultEncoding" value="utf-8" />    <!-- 文件大小最大值 -->    <property name="maxUploadSize" value="10485760000" />    <!-- 内存中的最大值 -->    <property name="maxInMemorySize" value="40960" />  </bean></beans>

4.2、配置web-
<??><web-app ="http://     ="http://www.w3.org/2001/     xsi:schemaLocation="http://     version="3.1"> <display-name>Archetype Created Web Application</display-name> <!-- Spring和mybatis的配置文件 --> <context-param>  <param-name>contextConfigLocation</param-name>  <param-value>classpath:ssm/spring-mybatis.</param-value> </context-param> <!-- 编码过滤器 --> <filter>  <filter-name>encodingFilter</filter-name>  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  <async-supported>true</async-supported>  <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> <!-- Spring监听器 --> <listener>  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止Spring内存溢出监听器 --> <listener>  <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <servlet>  <servlet-name>ssm</servlet-name>  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  <init-param>   <!--contextConfigLocation配置springMvc加载的配置文件(配置处理器,映射器,适配器等等)-->   <param-name>contextConfigLocation</param-name>   <param-value>classpath:ssm/spring-mvc.</param-value>   <!--如果不配置contextConfigLocation,默认加载/WEB-INF/servlet名称-servlet.-->  </init-param> </servlet> <servlet-mapping>  <servlet-name>ssm</servlet-name>  <!--第一种方式:*.action访问,.action结尾由DispatcherServlet解析-->  <!--第二种方式:/,所有访问的地址都有DispatcherServlet解析-->  <url-pattern>/</url-pattern> </servlet-mapping></web-app>

										
4.3、测试

至此,都已经整合了,在测试了的时候还是发现了很多错误,比如测试的时候maven中少了spring-dao.jar包导致测试无法通过,遇到错误不要怕多google

4.3.1、建立jsp页面

ShowUser.jsp只输出一个用户名

<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>  <title>showUser</title></head><body>  ${user}</body></html>

4.3.2、建立Controller类

UserController.java

package cn.controller;import cn.pojo.Emp;import cn.service.IEmpService;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;@Controllerpublic class UserController {  @Resource  private IEmpService iEmpService;  @RequestMapping("/showUser")  public String toIndex(HttpServletRequest request, Model model) throws Exception{    Emp user = this.iEmpService.findById("8888");    model.addAttribute("user", user.getEname());    return "showUser";  }}

4.3.3、最后部署一下即可

至此所有的整合已完成!!!