• JAVA SSM整合流程以及注意点


    1、搭建整合环境

          整合说明:SSM整合可以使用多种方式,咱们会选择XML + 注解的方式

    •  先搭建整合的环境
    •  先把Spring的配置搭建完成
    •  再使用Spring整合SpringMVC框架
    •  最后使用Spring整合MyBatis框架
    •  创建数据库和表结构

    4. 创建maven的工程(中间选择骨架时用到的键值对

    archetypeCatalog
    internal

    1.  创建ssm_parent父工程(打包方式选择pom,必须的)
    2. 创建ssm_web子模块(打包方式是war包)
    3.  创建ssm_service子模块(打包方式是jar包)
    4.  创建ssm_dao子模块(打包方式是jar包)
    5. 创建ssm_domain子模块(打包方式是jar包)
    6.  web依赖于service,service依赖于dao,dao依赖于domain
    7. 在ssm_parent的pom.xml文件中引入坐标依赖
     <properties>
        <spring.version>5.0.2.RELEASE</spring.version>
        <slf4j.version>1.6.6</slf4j.version>
        <log4j.version>1.2.12</log4j.version>
        <mysql.version>5.1.6</mysql.version>
        <mybatis.version>3.4.5</mybatis.version>
      </properties>
    

      

    <dependencies>
        <!-- spring -->
        <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjweaver</artifactId>
          <version>1.6.8</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aop</artifactId>
          <version>${spring.version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</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-webmvc</artifactId>
          <version>${spring.version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</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>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
          <scope>compile</scope>
        </dependency>
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>${mysql.version}</version>
        </dependency>
        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>servlet-api</artifactId>
          <version>2.5</version>
          <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>javax.servlet.jsp</groupId>
          <artifactId>jsp-api</artifactId>
          <version>2.0</version>
          <scope>provided</scope>
        </dependency>
        <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>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 -->
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>${mybatis.version}</version>
        </dependency>
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis-spring</artifactId>
          <version>1.3.0</version>
        </dependency>
        <dependency>
          <groupId>c3p0</groupId>
          <artifactId>c3p0</artifactId>
          <version>0.9.1.2</version>
          <type>jar</type>
          <scope>compile</scope>
        </dependency>
      </dependencies>
    

     5、依次编写实体类dao(接口,@Repository,将来连接数据库)、domain(bean实体类,与数据库对应)、service(里面有不同的实现类,@Service("accountService")

    实现接口方法),此时Service中不去连接数据库,方便检测Spring模块完好情况

     编写TestSpring类检测Spring模块是否正常运行

    import com.courage.service.AccountService;
    import org.junit.Test;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class TestSpring {
        @Test
        public void run1() {
    
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            AccountService accountService = (AccountService) context.getBean("accountService");
            accountService.findAll();
        }
    }

    上面一步完好之后,开始编写SpringMVC模块,即web.xml,Springmvc.xml,Controller.java

    web.xml
    <!--//前端控制器--> <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

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xmlns:context="http://www.springframework.org/schema/context"
           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.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
    
    
        <!--扫包-->
        <context:component-scan base-package="com.courage">
            <context:include-filter type="annotation"
                                    expression="org.springframework.stereotype.Controller"></context:include-filter>
        </context:component-scan>
        <!--配置视图解析器-->
        <bean id="internalResourceViewResolver" 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="/css/**" location="/css/"></mvc:resources>
        <mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
        <mvc:resources mapping="/images/**" location="/images/"></mvc:resources>
        <!--开启mvc注解扫描-->
        <mvc:annotation-driven></mvc:annotation-driven>
    </beans>

    Controller.java

    @Controller
    @RequestMapping("/account")
    public class AccountController {
        @Autowired
        private AccountService accountService;
        @RequestMapping("/findAll")
        public String findAll(Model model){
           
            System.out.println("表现层传数据");
            return "list";
        }

    WEB-INF下创建pages文件夹再创建list.jsp

    部署tomcat,启动

    成功之后整合Spring和SpringMVC,由于tomcat启动时依次扫描的是web.xml--->Springmvc.xml,全程都没有加载Spring的applicationContext.xml文件,而整合时需要将其加入容器中,因此设置监听器,步骤:

    需要导入spring-web这个jar包,因为默认只扫描Resourse目录,所以要context-param指定实际目录

    在SpringMVC的web.xml文件中加入下列监听器代码:

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

    此后applicationContext.xml会被加入到容器中

    此时在Controller中注解

    @Autowired
    private AccountService accountService;
    同时,调用
    accountService.findAll()方法

    在Service中注解
        @Autowired
        private AccountDao accountDao;

    同时,调用accountDao.findAll()方法
    若通过Controller层可以连接到Service --> dao层,则可以开始部署Mybatis层连接数据库



    先保证Mybatis模块可以正常运行,配置步骤:
    1、在Resource路径下添加SqlMapConfig.xml文件,用来连接数据库
    <?xml version="1.0" encoding="UTF-8"?>
    <!--Mybatis是跟数据库对接,所以要创建连接数据库的配置文件-->
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <environments default="mysql">
            <environment id="mysql">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql:///ssm"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                </dataSource>
            </environment>
        </environments>
        <!-- 使用的是注解,引入配置文件 -->
        <mappers><!--映射-->
            <!-- <mapper class="com.courage.dao.AccountDao"/> -->
            <!-- 该包下所有的dao接口都可以使用,Mybatis根据接口创建实现类 -->
            <package name="com.courage.dao"/><!--默认这个包所有的文件都可以扫到-->
        </mappers>
    </configuration>

     2、Mybatis测试类

         

    public class TestMybatis {
        @Test
        public void run1() throws Exception {
            //获取配置文件
            InputStream asStream = Resources.getResourceAsStream("MySqlMapConfig.xml");
            //创建工厂对象SqlSessionFactory
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(asStream);
            //工厂开始汇话
            SqlSession sqlSession = factory.openSession();
            //获取代理对象
            AccountDao dao = sqlSession.getMapper(AccountDao.class);
            //查询账户信息
            List<Account> list = dao.findAll();
            for (Account account : list) {
                System.out.println(account);
            }
    
            sqlSession.close();//关闭流
            asStream.close();
    
        }
    }
    成功后
    整合部署Mybatis步骤:

    1、在applicationContext.xml中补充连接池(连接数据库的四大要素、Mybatis工厂、Mapper)
    <!--Spring整合Mybatis-->
      <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql:///ssm"/>
        <property name="user" value="root"/>
        <property name="password" value="123456"/>
      </bean>
      <!--Mybatis工厂-->
      <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--//通过连接池(配置文件)连接数据库-->
        <property name="dataSource" ref="dataSource"></property>
      </bean>
      <!--Mybatis mapper-->
      <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.courage.dao"></property>
      </bean>
    
    
    <!--配置Spring框架声明式事务管理-->
    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <property name="dataSource" ref="dataSource" />
    </bean>
    
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
      <tx:attributes>
        <tx:method name="find*" read-only="true"/>
        <tx:method name="*" isolation="DEFAULT"/>
      </tx:attributes>
    </tx:advice>
    
    <!--配置AOP增强-->
    <aop:config>
      <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.courage.service.impl.*ServiceImpl.*(..))"/>
    </aop:config>

    其他步骤:

     在AccountDao接口中添加@Repository注解

    在service中注入dao对象,进行测试

  • 相关阅读:
    获取SpringMVC的映射路径
    Spring任务调度之Quartz集成
    Spring任务调度之SpringTask基于XML和基于注解的使用示例
    Redis分布式集群搭建
    京东软开实习岗
    C语言编程练习(一)
    servlet温习
    tomcat启动超过时间
    JDK版本更换,Eclipse中所有的项目报错
    Myeclipse2017C版本破解
  • 原文地址:https://www.cnblogs.com/Courage129/p/12713453.html
Copyright © 2020-2023  润新知