Maven+SSM整合.doc

Maven + SSM整合

1开发环境搭建
1.1Eclipse4.7(Oxygen) + Tomcat8 + Maven3.5.2
2Maven Web项目创建
2.1新建maven项目

 2.2 选择工作空间

2.3 选择创建web项目

2.4 填写项目相关参数

2.5 完成后的目录结构图

2.6修改为maven约定目录

1、点击项目右键Properties -> Java Build Path ->Source选项

2、点击项目右键new->Source Folder

3、修改index.jsp的错误

pom.xml添加servlet的支持

4、最终目录结构图

2.7 设置 Properties -> Project Facets

选中3.0 可能会出错

 

解决方法: 修改该项目路径下的 .settings/ org.eclipse.wst.common.project.facet.core.xml 文件

关闭项目再重新打开

3SSM整合
3.1Spring和Mybatis的整合
3.1.1Maven引入需要的Jar包
1、本教程使用部分jar的版本:
       Spring: 5.0.2.RELEASE
       Spring MVC: 5.0.2.RELEASE
       MyBatis:  3.4.5
       mybatis-spring:  1.3.0
       mysql-connector-java: 5.1.2
       javax.servlet-api:3.1.0 
       commons-dbcp: 1.4
       commons-io:  2.5
       commons-codec: 1.10
2、pom.xml
<properties>  
       <!-- spring版本号 -->  
       <spring.version>5.0.2.RELEASE</spring.version>  
       <!-- mybatis版本号 -->  
       <mybatis.version>3.4.5</mybatis.version>  
       <!-- log4j日志文件管理包版本 -->  
       <slf4j.version>1.7.7</slf4j.version>  
       <log4j.version>1.2.17</log4j.version>  
 
 <dependencies>
       <dependency>
           <groupId>junit</groupId>

   </properties>
           <artifactId>junit</artifactId>
         <version>4.12</version>
           <!-- 表示开发的时候引入,发布的时候不会加载此包 -->
           <scope>test</scope>
       </dependency>
       <dependency>
           <groupId>javax.servlet</groupId>
           <artifactId>javax.servlet-api</artifactId>
           <version>3.1.0</version>
       </dependency>
       <!-- spring核心包 -->
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-core</artifactId>
           <version>${spring.version}</version>
       </dependency>

       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-web</artifactId>
           <version>${spring.version}</version>
       </dependency>
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-oxm</artifactId>
           <version>${spring.version}</version>
       </dependency>
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-tx</artifactId>
           <version>${spring.version}</version>
       </dependency>

       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-jdbc</artifactId>
           <version>${spring.version}</version>
       </dependency>

       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-webmvc</artifactId>
           <version>${spring.version}</version>
       </dependency>
       <dependency>

          <groupId>org.springframework</groupId>
           <artifactId>spring-aop</artifactId>
           <version>${spring.version}</version>
       </dependency>

       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-context-support</artifactId>
           <version>${spring.version}</version>
       </dependency>

       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-test</artifactId>
           <version>${spring.version}</version>
       </dependency>
       <!-- mybatis核心包 -->
       <dependency>
           <groupId>org.mybatis</groupId>
           <artifactId>mybatis</artifactId>
           <version>${mybatis.version}</version>
       </dependency>
       <!-- mybatis/spring包 -->
       <dependency>
           <groupId>org.mybatis</groupId>
           <artifactId>mybatis-spring</artifactId>
           <version>1.3.0</version>
       </dependency>
       <!-- 导入java ee jar 包 -->
       <dependency>
           <groupId>javax</groupId>
           <artifactId>javaee-api</artifactId>
           <version>7.0</version>
       </dependency>
       <!-- 导入Mysql数据库链接jar包 -->
       <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>5.1.2</version>
       </dependency>
       <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
       <dependency>
           <groupId>commons-dbcp</groupId>
           <artifactId>commons-dbcp</artifactId>


           <version>1.4</version>
       </dependency>
       <!-- JSTL标签类 -->
       <dependency>
           <groupId>jstl</groupId>
           <artifactId>jstl</artifactId>
           <version>1.2</version>
       </dependency>
       <!-- 日志文件管理包 -->
       <!-- log start -->
       <dependency>
           <groupId>log4j</groupId>
           <artifactId>log4j</artifactId>
           <version>${log4j.version}</version>
       </dependency>
       
       <!-- 格式化对象,方便输出日志 -->
       <dependency>
           <groupId>com.alibaba</groupId>
           <artifactId>fastjson</artifactId>
           <version>1.2.17</version>
       </dependency>

       <dependency>
           <groupId>org.slf4j</groupId>
           <artifactId>slf4j-api</artifactId>
           <version>${slf4j.version}</version>
       </dependency>

       <dependency>
           <groupId>org.slf4j</groupId>
           <artifactId>slf4j-log4j12</artifactId>
           <version>${slf4j.version}</version>
       </dependency>
       <!-- log end -->

       <!-- 映入JSON -->
       <dependency>
           <groupId>org.codehaus.jackson</groupId>
           <artifactId>jackson-mapper-asl</artifactId>
           <version>1.9.13</version>
       </dependency>
       <dependency>
           <groupId>com.fasterxml.jackson.core</groupId>

         <artifactId>jackson-core</artifactId>
           <version>2.9.2</version>
       </dependency>
       <dependency>
           <groupId>com.fasterxml.jackson.core</groupId>
           <artifactId>jackson-databind</artifactId>
           <version>2.9.2</version>
       </dependency>
       <dependency>
           <groupId>com.fasterxml.jackson.core</groupId>
           <artifactId>jackson-annotations</artifactId>
           <version>2.9.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.5</version>
       </dependency>
       <dependency>
           <groupId>commons-codec</groupId>
           <artifactId>commons-codec</artifactId>
           <version>1.10</version>
       </dependency>
 </dependencies>

3.1.2 建立JDBC属性文件(文件编码修改为utf-8):

 

jdbc.driver_class=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///ssm
jdbc.username=root
jdbc.password=root
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000

 

3.1.3 建立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:mybatis-spring="http://mybatis.org/schema/mybatis-spring" 
  xmlns:tx="http://www.springframework.org/schema/tx" 
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xsi:schemaLocation="
    http://mybatis.org/schema/mybatis-spring 
    http://mybatis.org/schema/mybatis-spring-1.3.xsd
    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/mvc  
    http://www.springframework.org/schema/mvc/spring-mvc.xsd

   http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 支持注解 -->
    <context:annotation-config></context:annotation-config>
        <!--自动扫描 :通过注解过滤被扫描的类 -->  
        <context:component-scan base-package="com.bw" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
    </context:component-scan>
    
    <!-- 引入配置文件 -->
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver_class}" />
        <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.xml文件 -->

        <property name="mapperLocations" value="classpath*:com/bw/mapper/*.xml"></property>
    </bean>

    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.bw.mapper" />
        <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.1.4JUnit测试Mybatis
3.1.4.1创建测试用表
DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `username` 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` */

INSERT  INTO `user`(`id`,`username`,`password`,`age`) VALUES (1,'test1','pwd1',21);
INSERT  INTO `user`(`id`,`username`,`password`,`age`) VALUES (2,'test2','pwd2',22);
INSERT  INTO `user`(`id`,`username`,`password`,`age`) VALUES (3,'测试3','pwd2',23);
3.1.4.2利用MyBatis Generator自动创建代码

这个可根据表自动创建实体类、MyBatis映射文件以及mapper接口;完成后将文件复制到工程中。如图:

3.1.4.3 创建Service接口和实现类

1service接口

2service的实现类

3.1.4.4创建测试类TestMyBatis
测试类在src/test/java中建立TestMyBatis。

如果测试成功,表示SpringMybatis已经整合成功了。

 

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

3.2整合SpringMVC
3.2.1配置web.xml文件
这里面对spring-mybatis.xml的引入以及配置了spring-mvc的Servlet核心控制器就是为了完成SSM整合。
<?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"
version="3.0"> <display-name>Archetype Created Web Application</display-name> <!-- Spring和mybatis的配置文件的路径 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</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> <!-- Spring MVC servlet核心控制器 --> <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:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 --> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> </web-app>
3.2.2配置spring_mvc.xml文件
配置里面的注释也很详细,在此就不说了;主要是自动扫描控制器,视图模式,注解的启动这三个。
**注意:**配置文件中的一行:
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" 我的项目里是jackson2.X版本的,如果你用的是jackson1.X版本的,不用写"2"。
<?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:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
    xmlns:tx="http://www.springframework.org/schema/tx" 
  xmlns:context
="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.3.xsd 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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 支持注解 --> <context:annotation-config></context:annotation-config> <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 (通过注解过滤被扫描的类) --> <context:component-scan base-package="com.bw"></context:component-scan> <!-- 解决Spring MVC @ResponseBody返回中文字符串乱码问题 --> <bean class="org.springframework.web.servlet.
        mvc.method.annotation.RequestMappingHandlerAdapter"
> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.
                  StringHttpMessageConverter"
> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=utf-8</value> <value>text/html;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean> <mvc:annotation-driven /> <!--避免IE执行AJAX时,返回JSON出现下载文件;注意:MappingJackson2 --> <bean id="mappingJacksonHttpMessageConverter"    class="org.springframework.http.converter.json.
          MappingJackson2HttpMessageConverter"
> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>text/plain;charset=utf-8</value> </list> </property> </bean> <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.
            mvc.annotation.AnnotationMethodHandlerAdapter"
> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 --> </list> </property> </bean> <!-- 定义跳转的文件的前后缀 ,视图模式配置 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀
      ,变成一个 可用的url地址
--> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,
    那么配置文件中也不必引入上传组件包
--> <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>
3.2.3Junit测试SpringMVC
3.2.3.1创建UserController类

3.2.3.2创建测试类TestController
1、编写测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { 
      "classpath:spring-mybatis.xml", "classpath:spring-mvc.xml" }) @WebAppConfiguration public class TestController { private MockMvc mockMvc; @Autowired protected WebApplicationContext wac; @Before() // 这个方法在每个方法执行之前都会执行一遍 public void setup() { mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); // 初始化MockMvc对象 } @Test public void getAllCategoryTest() throws Exception { String responseString = mockMvc.perform(get("/user/showUser") // 请求的url,请求的方法是get // get("/user/showUser2") //请求的url,请求的方法是get .contentType(MediaType.APPLICATION_FORM_URLENCODED)// 数据的格式 .param("id", "1") // 添加参数(可以添加多个) // .param("id","3") //添加参数(可以添加多个) ).andExpect(status().isOk()) // 返回的状态是200 .andDo(print()) // 打印出请求和相应的内容 .andReturn().getResponse().getContentAsString(); // 将相应的数据转换为字符串 System.out.println("-----返回的json = " + responseString); } }

2、控制台打印结果:

 

4Tomcat启动Maven项目
1、点击项目右键,Properties->Project Facets

2

 

 

posted @ 2019-03-20 17:01  lilixia  阅读(366)  评论(0编辑  收藏  举报