zoukankan      html  css  js  c++  java
  • SSM整合

    整合思路

      Spring的IOC特性,所以应该是将别的框架整合到Spring中

         前置

      准备pom文件(可以分步导入,这里是一次性导入)

      

    <?xml version="1.0" encoding="UTF-8"?>

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.company</groupId>
    <artifactId>ssm</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>ssm Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <spring.version>5.0.2.RELEASE</spring.version>
    <mysql.version>5.1.6</mysql.version>
    <slf4j.version>1.6.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
    <mybatis.version>3.4.5</mybatis.version>
    </properties>

    <dependencies>
    <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
    </dependency>

    <!--这一个就将spring依赖的核心jar包导得差不多了-->
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <!--spring整合junit测试-->
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <!--spring管理数据库相关,传递依赖spring-tx-->
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <!--解析切入AOP表达式等-->
    <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.2</version>
    </dependency>


    <!--标准标签库-->
    <dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
    </dependency>
    <!--jsp-api会依赖导入servlet-api-->
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.0</version>
    </dependency>
    <!-- log start -->
    <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>${log4j.version}</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 -->

    <!--MyBatis-->
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>${mybatis.version}</version>
    </dependency>
    <!--spring整合MyBatis-->
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.1</version>
    </dependency>
    <!--连接池-->
    <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.9</version>
    </dependency>
    <!--数据库连接驱动-->
    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql.version}</version>
    </dependency>

    </dependencies>

    <build>
    <finalName>ssm</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
    <plugins>
    <plugin>
    <artifactId>maven-clean-plugin</artifactId>
    <version>3.1.0</version>
    </plugin>
    <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
    <plugin>
    <artifactId>maven-resources-plugin</artifactId>
    <version>3.0.2</version>
    </plugin>
    <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.0</version>
    </plugin>
    <plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.1</version>
    </plugin>
    <plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>3.2.2</version>
    </plugin>
    <plugin>
    <artifactId>maven-install-plugin</artifactId>
    <version>2.5.2</version>
    </plugin>
    <plugin>
    <artifactId>maven-deploy-plugin</artifactId>
    <version>2.8.2</version>
    </plugin>
    </plugins>
    </pluginManagement>
    </build>
    </project>

      

      jdbcConfig.properties

    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.username=root
    jdbc.password=yourPassword
    jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8

    第一步:

    配置Spring框架

    applicationContext.xml

    <!--配置spring注解扫描-->
    <context:component-scan base-package="com.company">
    <!--Controller的部分交给SpringMVC去扫描-->
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    导好spring的包然后在applicationContext.xml中配置注解扫描,就算是配置好Spring框架了,动手测试一下,写个Service,配上@Service("accountService")注解,findAll方法打印一句话验证有运行就可以了

    @Test
    public void testService(){
    ApplicationContext ac=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    AccountService accountService = ac.getBean("accountService", AccountService.class);
    accountService.findAll();

    }

    第二步:

    配置SpringMVC框架

    导入spring-mvcweb包

    web.xml

     <!--配置springMVC的前端控制器-->

    <servlet>
    <servlet-name>dispatcherServlet</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>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--配置编码过滤器,解决中文乱码问题-->
    <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.xml

      

    <!--springMvc的注解扫描,此处有一个巨坑,use-default-filters默认值为true,会扫描所有注入的注解
    如果只配置<context:include-filter>则还是表示啥都扫描,会导致事务管理器被SpringMVC管理,而不是Spring
    SpringMVC的容器是Spring的子容器,子容器可以访问父容器,父容器不可以访问子容器,有点类似于继承
    从软件层面上来说,Spring MVC是展示层可以调用业务层,业务层不能调用展示层。
    参考博客:https://www.cnblogs.com/Esummer/p/11791468.html
    结果就导致事务控制失败。
    <context:include-filter>和use-default-filters="false"配合使用才能达到“只扫描。。。”的目的
    -->
    <context:component-scan base-package="com.company" use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:include-filter>
    </context:component-scan>

    <!--配置视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/pages/"></property>
    <property name="suffix" value=".jsp"></property>
    </bean>

    <!--配置放行静态资源,可配置多个-->
    <mvc:resources mapping="/js/**" location="/js/"></mvc:resources>

    <!--开启springMVC注解的支持-->
    <mvc:annotation-driven/>

     这时候就可以写一个Controller类打上Controller注解,并配置好@RequestMapping访问路径,就可以配置tomcat访问一下试试,看SpringMVC是否工作正常

    第三步:

    整合Spring和SpringMVC框架

    web.xml添加内容,我的applicationContext.xml在resources目录下

    <!--整合Spring,使用ServletContextListener,此时只会加载/WEB-INF/applicationContext.xml文件-->
    <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--Spring配置文件在其他地方需要配置-->
    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    整合完毕,此时可以在Controller代码里注入Service对象,并调用Service中的方法。启动Tomcat访问Controller中的方法,看Service中的方法是否也被调用了。

    第四步:

    配置MyBatis框架

    确定MyBatis的包导入后

    SqlMapConfig.xml,当和Spring框架整合完毕,这个配置文件就不再需要了

    <?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>
    <!--加载jdbc配置文件-->
    <properties resource="jdbcConfig.properties"></properties>
    <!--为实体类起别名-->
    <typeAliases>
    <package name="com.company.entity"></package>
    </typeAliases>
    <!--配置环境-->
    <environments default="mysql">
    <environment id="mysql">
    <transactionManager type="JDBC"></transactionManager>
    <dataSource type="POOLED">
    <property name="driver" value="${jdbc.driver}"></property>
    <property name="url" value="${jdbc.url}"></property>
    <property name="username" value="${jdbc.username}"></property>
    <property name="password" value="${jdbc.password}"></property>
    </dataSource>
    </environment>
    </environments>
    <!--设置接口扫描包-->
    <mappers>
    <package name="com.company.dao"></package>
    </mappers>
    </configuration>

    我习惯XML配置映射的方式写Sql,也可以用注解的方式。在resources文件夹创建与Dao接口所在包相同结构的文件夹,并创建同名的xml文件

    com/company/dao/AccountDao.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.company.dao.AccountDao">
    <select id="findAll" resultType="account">
    SELECT * FROM account
    </select>
    <update id="save" parameterType="account">
    INSERT INTO account (name,money) VALUES (#{name},#{money})
    </update>
    </mapper>

    测试一把

      

        @Test
    public void testMyBatis() throws IOException {
    InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
    SqlSession sqlSession = factory.openSession();
    AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
    // List<Account> list = accountDao.findAll();
    // for (Account account : list) {
    // System.out.println(account);
    // }
    Account account=new Account();
    account.setName("ddd");
    account.setMoney(666d);
    accountDao.save(account);
         //注意此处需要手动commit
    sqlSession.commit();
    in.close();
    sqlSession.close();
    }

      

    第五步:

    Spring整合MyBatis框架

    确认mybatis-spring包有正常导入

    applicationContext.xml添加内容,整合部分

      

     
    <!--引入jdbc配置文件-->
    <context:property-placeholder location="classpath:jdbcConfig.properties"/>

    <!--整合MyBaties↓-->
    <!--1.准备连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="${jdbc.driver}"></property>
    <property name="url" value="${jdbc.url}"></property>
    <property name="username" value="${jdbc.username}"></property>
    <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!--2.配置MyBatis的SQLSession工厂-->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <!--配置实体类别名,多个包在value值中使用“;”进行分隔-->
    <property name="typeAliasesPackage" value="com.company.entity"></property>
    </bean>
    <!--3.配置myBatis扫描的包-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.company.dao"></property>
    </bean>
    <!--整合MyBaties↑-->

    applicationContext.xml添加内容,事务管理部分

      

    <!--事务控制↓-->
    <!--事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--切入点配置-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
            <!--关于事务属性配置可以参考https://www.cnblogs.com/zou-rong/p/12047768.html-->
    <tx:method name="*" propagation="REQUIRED" read-only="false"/>
    <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
    </tx:attributes>
    </tx:advice>
    <!--配置事务管理器和切入点增强方法-->
    <aop:config>
    <aop:pointcut id="pt1" expression="execution(* com.company.service.impl.*.*(..))"></aop:pointcut>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
    </aop:config>
    <!--事务控制↑-->

    此时可以在Dao接口上加上@Repository注解,然后在Service中调用dao的方法,在index.jsp中写一个表单提交,看看是否能保存成功,再在保存后添加一个异常int i=10/0;重新测试能否回滚。

    都没有问题就可以删除SqlMapConfig.xml文件了

    到此SSM整合完毕。----------------------------------------------------------------------------------------------------------------------

    下面贴出完整的整合配置文件

    web.xml

      

    <!DOCTYPE web-app PUBLIC
    "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd" >

    <web-app>
    <display-name>Archetype Created Web Application</display-name>
    <!--整合Spring,使用ServletContextListener,此时只会加载/WEB-INF/applicationContext.xml文件-->
    <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--Spring配置文件在其他地方需要配置-->
    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!--配置springMVC的前端控制器-->
    <servlet>
    <servlet-name>dispatcherServlet</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>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--配置编码过滤器,解决中文乱码问题-->
    <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>

    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:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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">

    <!--引入jdbc配置文件-->
    <context:property-placeholder location="classpath:jdbcConfig.properties"/>
    <!--配置spring注解扫描-->
    <context:component-scan base-package="com.company">
    <!--Controller的部分交给SpringMVC去扫描-->
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!--整合MyBaties↓-->
    <!--1.准备连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="${jdbc.driver}"></property>
    <property name="url" value="${jdbc.url}"></property>
    <property name="username" value="${jdbc.username}"></property>
    <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!--2.配置MyBatis的SQLSession工厂-->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <!--配置实体类别名,多个包在value值中使用“;”进行分隔-->
    <property name="typeAliasesPackage" value="com.company.entity"></property>
    </bean>
    <!--3.配置myBatis扫描的包-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.company.dao"></property>
    </bean>
    <!--整合MyBaties↑-->

    <!--事务控制↓-->
    <!--事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--切入点配置-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
    <tx:method name="*" propagation="REQUIRED" read-only="false"/>
    <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
    </tx:attributes>
    </tx:advice>
    <!--配置事务管理器和切入点增强方法-->
    <aop:config>
    <aop:pointcut id="pt1" expression="execution(* com.company.service.impl.*.*(..))"></aop:pointcut>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
    </aop:config>
    <!--事务控制↑-->
    </beans>

    springMvc.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: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">
    <!--springMvc的注解扫描,此处有一个巨坑,use-default-filters默认值为true,会扫描所有注入的注解
    如果只配置<context:include-filter>则还是表示啥都扫描,会导致事务管理器被SpringMVC管理,而不是Spring
    SpringMVC的容器是Spring的子容器,子容器可以访问父容器,父容器不可以访问子容器,有点类似于继承
    从软件层面上来说,Spring MVC是展示层可以调用业务层,业务层不能调用展示层。
    参考博客:https://www.cnblogs.com/Esummer/p/11791468.html
    结果就导致事务控制失败。
    <context:include-filter>和use-default-filters="false"配合使用才能达到“只扫描。。。”的目的
    -->

    <context:component-scan base-package="com.company" use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:include-filter>
    </context:component-scan>

    <!--配置视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/pages/"></property>
    <property name="suffix" value=".jsp"></property>
    </bean>

    <!--配置放行静态资源-->
    <mvc:resources mapping="/js/**" location="/js/"></mvc:resources>

    <!--开启springMVC注解的支持-->
    <mvc:annotation-driven/>
    </beans>

    pom.xml和jdbcConfig.properties都在最开始给出,此处不再赘述,不足之处还请各位看官不吝赐教。

  • 相关阅读:
    【vue开发问题-解决方法】(六)axios报错问题,Cannot read property 'protocol' of undefined
    【vue开发问题-解决方法】(五)vue Element UI 日期选择器获取日期格式问题 t.getTime is not a function
    【vue开发问题-解决方法】(四)vue Element UI使用中.$scopedSlots.default is not a function 报错
    【vue开发问题-解决方法】(三)axios拦截器,post请求问题处理,异步请求封装
    【vue开发问题-解决方法】(二)element UI日期控件失效RangeError:Maximum call stack size exceeded
    【vue开发问题-解决方法】(一)在style中设置background-image时路径问题
    异常分析
    如何理解spring MVC
    解决项目不编译4大clean
    java中的生产者模式
  • 原文地址:https://www.cnblogs.com/zou-rong/p/12525620.html
Copyright © 2011-2022 走看看