• spring-第N篇整合SSM,即Mybatis+Spring+Spring MVC


    1、Mybatis的配置使用

       1》Jar包:mybatis-3.4.5.jar、mysql-connector-6.0.2或者ojdbc6-11.2.0.4.jar。

       2》编写conf.xml,用于构建SqlSessionFactory。

    <?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>
    
        <settings>
           <!-- 配置用于控制台输出sql日志。低版本的mybatis不支持logImpl -->
           <setting name="logImpl" value="LOG4J"/>
        </settings>
        
        <environments default="oracle">
            <environment id="oracle">
                <!-- 指定事务管理类型,type="JDBC"指直接使用JDBC的提交与回滚   -->
                <transactionManager type="JDBC" />
                <!-- 配置数据库连接信息 -->
                <dataSource type="POOLED">
                    <property name="driver" value="oracle.jdbc.OracleDriver" />
                    <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl" />
                    <property name="username" value="scott" />
                    <property name="password" value="scott" />
                </dataSource>
            </environment>
            <environment id="mysql">
                <transactionManager type="JDBC" />
                <!-- 配置数据库连接信息 -->
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver" />
                    <property name="url" value="jdbc:mysql://127.0.0.1:3306/world" />
                    <property name="username" value="root" />
                    <property name="password" value="root" />
                </dataSource>
            </environment>
        </environments>
        
        <mappers>
            <!-- 注册empMapper.xml文件-->
            <mapper resource="com/lfy/mapping/empMapper.xml"/>
        </mappers>
        
    </configuration>

       3》编写mapper.xml、或者使用注解、或者mapper接口。

    <?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-->
    <mapper namespace="com.lfy.mapping.empMapper">
        <select id="getEmp" parameterType="int" resultType="com.lfy.bean.Emp">
            select * from emp where empno=#{empno}
        </select>
    </mapper>

       4》获取SqlSession,使用SqlSession调用相关方法进行数据库操作。

    package com.lfy.Util;
    
    import java.io.InputStream;
    
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    public class MyBatisUtil {
    
        /**
         * 获取SqlSessionFactory
         * @return SqlSessionFactory
         */
        public static SqlSessionFactory getSqlSessionFactory() {
            String resource = "conf.xml";
            InputStream is = MyBatisUtil.class.getClassLoader().getResourceAsStream(resource);
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
            return factory;
        }
        
        /**
         * 获取SqlSession
         * @return SqlSession
         */
        public static SqlSession getSqlSession() {
            return getSqlSessionFactory().openSession();
        }
        
        /**
         * 获取SqlSession
         * @param isAutoCommit 
         *         true 表示创建的SqlSession对象在执行完SQL之后会自动提交事务
         *         false 表示创建的SqlSession对象在执行完SQL之后不会自动提交事务,这时就需要我们手动调用sqlSession.commit()提交事务
         * @return SqlSession
         */
        public static SqlSession getSqlSession(boolean isAutoCommit) {
            return getSqlSessionFactory().openSession(isAutoCommit);
        }
        
        /**
         * 获取对应的mapper接口
         * @param clazz
         * @return
         */
        public static <T> T getMapper(Class<T> clazz){
            return getSqlSessionFactory().openSession().getMapper(clazz);
        }
        
        /**
         * 获取对应的mapper接口
         * @param clazz mapper接口类型
         * @param isAutoCommit 
         *         true 表示创建的SqlSession对象在执行完SQL之后会自动提交事务
         *         false 表示创建的SqlSession对象在执行完SQL之后不会自动提交事务,这时就需要我们手动调用sqlSession.commit()提交事务
         * @return
         */
        public static <T> T getMapper(Class<T> clazz,boolean isAutoCommit){
            return getSqlSessionFactory().openSession(isAutoCommit).getMapper(clazz);
        }
    }

    2、Spring的配置使用

       1》Jar包:spring、commons-logging.1.2.jar、aspectj-1.8.0.jar、aopalliance-1.0.jar

       2》编写beans.xml,注册spring Bean。

    <?xml version="1.0" encoding="UTF-8"?>
    <!-- spring配置文件的根元素,使用spring-beans-4.0.xsd语义约束 -->
    <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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
           http://www.springframework.org/schema/context 
           http://www.springframework.org/schema/context/spring-context-4.0.xsd  
           http://www.springframework.org/schema/aop 
           http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
          
           <!-- 指定自动搜索bean组件、自动搜索切面类 -->
           <context:component-scan base-package="com.lfy.aspect,com.lfy.impl">
               <context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>
           </context:component-scan>
           
           
           <!-- 或者不打算使用spring的xml schema配置方式,则应该在spring配置文件中增加如下片段
                                    来启动@AspectJ的支持  
               <bean class="org.springframework.aop.aspectj.annotation.
                            AnnotationAwareAspectJAutoProxyCreator"/>
                                    为了在spring应用中启动@AspectJ的支持,还需要在应用的类加载路径下增加两个AspectJ库:
               aspectjweaver.jar和aspectjrt.jar,除此之外,spring AOP还依赖aopalliance.jar
           -->
           <!-- 启动@AspectJ支持  -->
           <aop:aspectj-autoproxy/>
           
           
           <!-- 完全不打算使用spring的xml schema配置方式使用spring AOP,即bean的注册也使用注解的形式。
                                       应该加入如下代码 ,AnnotationAwareAspectJAutoProxyCreator是一个bean后处理器,该bean
                                       后处理器将会为容器中的所有bean生成AOP代理
           -->
           <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"/>
    </beans>

       3》编写相关的bean或者AOP切面。可以是注解类型的、也可以是bean配置文件配置的,切面有5种类型(before、around、afterThrowing、afterReturning、after)。

       4》根据beans.xml创建ApplicationContext,根据ApplicationContext获取容器中的bean使用。

    3、Spring MVC的配置使用

       1》Jar包:spring、commons-logging-1.2.jar

       2》在Web.xml中配置前端控制器,并引入springmvc-config.xml

    <?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" id="WebApp_ID" version="3.0">
      <display-name>springMVCInterceptorTest-1.0.0</display-name>
      
      <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*:config/spring/springmvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
      </servlet>
      <!-- 让Spring MVC的前端控制器拦截所有请求 -->
      <servlet-mapping>
        <servlet-name>springmvc</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>
            <!--  
            <init-param>
                <param-name>forceEncoding</param-name>
                <param-value>true</param-value>
            </init-param> -->
       </filter>
       <filter-mapping>
            <!-- 或者 <filter-name>encodingFilter</filter-name> -->
              <filter-name>characterEncodingFilter</filter-name>  
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    </web-app>

        springmvc-config.xml

    <?xml version="1.0" encoding="utf-8"?>
    <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns="http://www.springframework.org/schema/beans"
           xmlns:p="http://www.springframework.org/schema/p"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="
           http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-4.0.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">
           
          <mvc:default-servlet-handler/>
          
    <!-- 扫描控制器 --> <context:component-scan base-package="com.lfy.controller"/> <!-- 映射器、适配器策略 --> <mvc:annotation-driven/> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/content/" p:suffix=".jsp" /> </beans>

       3》@Controller编写控制器、@RequestMapping配置处理方法路径。额外的增加自定义类型转换器、拦截器。

    4、Mybatis+Spirng+Spring MVC的配置使用(常规复制jar包的形式)

      1》搭建的jar包

        1>springframework框架jar包。springframework-5.0.1框架jar包+commons-logging-1.2日志jar包

        2>Mybatis框架jar包。mybatis-3.4.5.jar及mybatis-3.4.5包下lib文件所有的jar包:cblib-3.2.5.jar、javassist-3.22.0-CR2.jar、log4j-1.2.17.jar、log4j-api-2.3.jar、log4j-core-2.3.jar、ognl-3.1.15.jar等。

        3>Mybatis整合spring中间件的jar包。mybatis-spring-1.3.1.jar,主要作用是:

             1>>在spring中配置Mybatis工厂类

             2>>在DAO层使用spring注入的工具Bean对数据进行操作。

        4>aspectj框架jar包。aspectjrt.jar、aspectjtools.jar、aspectjweaver.jar、org.aspectj.matcher.jar。

        5>AOP联盟jar包。aopalliance.jar。

        6>数据库驱动包。mysql-connector-java-5.1.30.jar。

        7>数据源c3p0所需的jar包。c3p0-0.9.5.2.jar、hibernate-c3p0-4.3.5.Final.jar、mchange-commons-java-0.2.1.1.jar。

        8>jsp、JSTL标签库jar包。javax.servlet.jsp.jstl-1.2.1.jar、javax.servlet.jsp.jstl-api-1.2.1.jar

      2》项目目录结构

        

      db.properties

    dataSource.driverClass=com.mysql.jdbc.Driver
    dataSource.jdbcUrl=jdbc:mysql://127.0.0.1:3306/mybatis
    dataSource.user=root
    dataSource.password=root
    dataSource.maxPoolSize=20
    dataSource.maxIdleTime = 1000
    dataSource.minPoolSize=6
    dataSource.initialPoolSize=5

      web.xml:整合spring、springMVC

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
        http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 
        id="WebApp_ID" version="3.1">
        
        <display-name>springMybatisSpringMVC-1.0.0</display-name>
        
        <!-- 配置spring核心监听器,默认会以 /WEB-INF/applicationContext.xml作为配置文件 -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <!-- contextConfigLocation参数用来指定Spring的配置文件 -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/applicationContext*.xml</param-value>
        </context-param>
        
        <!-- 定义Spring MVC的前端控制器 -->
      <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>/WEB-INF/springmvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
      </servlet>
      
      <!-- 让Spring MVC的前端控制器拦截所有请求 -->
      <servlet-mapping>
        <servlet-name>springmvc</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>

       springmvc-config.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:mvc="http://www.springframework.org/schema/mvc"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        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">
            
        <mvc:default-servlet-handler/>
            
        <context:component-scan base-package="com.lfy.controller"/>
        
        <!-- 映射器、适配器 -->
        <mvc:annotation-driven/>
        
         <bean id="viewResolver"
              class="org.springframework.web.servlet.view.InternalResourceViewResolver"
              p:prefix="/WEB-INF/content/" p:suffix=".jsp"/> 
        
    </beans>

      applicationContext.xml:整合Mybatis

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" 
        xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        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/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
                            http://mybatis.org/schema/mybatis-spring 
                            http://mybatis.org/schema/mybatis-spring.xsd ">
           
        <!-- 扫描com.lfy包下面的java文件,有Spring的相关注解的类,则把这些类注册为Spring的bean -->
        <context:component-scan base-package="com.lfy"/>
        
        <!-- 使用PropertyOverrideConfigurer后处理器加载数据源参数 -->
        <context:property-override location="classpath:db.properties"/>
    
        <!-- 配置c3p0数据源 -->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"/>
        
        <!-- 配置SqlSessionFactory,org.mybatis.spring.SqlSessionFactoryBean是Mybatis社区开发用于整合Spring的bean -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
            p:dataSource-ref="dataSource"/> 

          <!-- mybatis:scan会将com.lfy.mapper包里的所有接口当作mapper配置,之后可以自动引入mapper类-->
          <mybatis:scan base-package="com.lfy.mapper"/>

        <!-- JDBC事务管理器 -->
        <bean id="transactionManager" 
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
             p:dataSource-ref="dataSource"/>
        
        <!-- 启用支持annotation注解方式事务管理 -->
        <tx:annotation-driven transaction-manager="transactionManager"/>
        
    </beans>

    5、Mybatis+Spring+SpringMVC的配置使用(Maven) 

      1》项目目录结构

         

      2》引入依赖

    <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/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      
      <groupId>com.lfy.cn</groupId>
      <artifactId>mavenMybatisSpringSpringMVC-1.0.0</artifactId>
      <packaging>war</packaging>
      <version>0.0.1-SNAPSHOT</version>
      
      <name>mavenMybatisSpringSpringMVC-1.0.0 Maven Webapp</name>
      <url>http://maven.apache.org</url>
      
      <properties>
        <!-- 自定义的spring的版本号 -->
        <spring.version>5.0.1.RELEASE</spring.version>
        <!-- 自定义的mybaits的版本号 -->
        <mybatis.version>3.4.5</mybatis.version>
        <!-- 自定义的mybaits-spring的版本号 -->
        <mybatis.spring.version>1.3.1</mybatis.spring.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
      
      <dependencies>
        <!-- springMVC的jar包,由于springMVC依赖 springBeans,springContext,springCore 所以这些jar包会被导入进来-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
            <scope>compile</scope>
        </dependency>
        <!-- spring-tx 事务 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
            <scope>compile</scope>
        </dependency>
        <!-- spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
            <scope>compile</scope>
        </dependency>
        <!-- aspectjweaver aop 依赖该jar包-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>
        
        <!-- servlet的jar包  begin -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>compile</scope> 
        </dependency>
        <!-- servlet.jsp-api -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
            <scope>provided</scope>
        </dependency>
        <!-- javax.servlet.jsp.jstl-api -->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>javax.servlet.jsp.jstl-api</artifactId>
            <version>1.2.2</version>
        </dependency>
        <!-- taglibs-standard-impl jstl的实现 -->
        <dependency>
            <groupId>org.apache.taglibs</groupId>
            <artifactId>taglibs-standard-impl</artifactId>
            <version>1.2.5</version>
        </dependency>
        <!-- servlet的jar包  end -->
    
        <!-- mybatis begin -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
            <scope>compile</scope>
        </dependency>
        <!-- mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatis.spring.version}</version>
            <scope>compile</scope>
        </dependency>
        <!--druid 连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
            <scope>compile</scope>
        </dependency>
        <!-- mysql的连接驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <!-- mybatis end -->
    
        <!--log4j2 begin -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-web</artifactId>
            <version>2.1</version>
        </dependency>
        <!--log4j2 end -->
        
        <!-- junit -->
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.11</version>
          <scope>test</scope>
        </dependency>
      </dependencies>
      
      <build>
        <finalName>mavenMybatisSpringSpringMVC-1.0.0</finalName>
      </build>
    </project>

      3》web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
        http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 
        id="WebApp_ID" version="3.1">
        
        <display-name>mavenMybatisSpringSpringMVC-1.0.0</display-name>
      
        <!-- 配置编码  -->
        <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>
          <init-param>
                 <param-name>forceRequestEncoding</param-name>
                 <param-value>true</param-value>
          </init-param>
          <init-param>
                 <param-name>forceResponseEncoding</param-name>
                 <param-value>true</param-value>
          </init-param>
        </filter>
        <filter-mapping>
          <filter-name>characterEncodingFilter</filter-name>
          <url-pattern>/*</url-pattern>
        </filter-mapping>
    
        <!-- spring IOC容器  -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/applicationContext-*.xml</param-value>
        </context-param>
        <!-- 加载监听器 -->
        <listener>
          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    
        <!-- 配置spring mvc的前端控制器 -->
        <servlet>
            <servlet-name>spring-mvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <!-- 本地的上下文配置   加载springmvc的配置文件 -->
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:spring/springmvc-config.xml</param-value>
            </init-param>
            <!-- 启动容器的时候加载 -->
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>spring-mvc</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
        
        <!-- log4j2-begin -->
         <context-param>  
            <param-name>isLog4jAutoInitializationDisabled</param-name>  
            <param-value>false</param-value>  
         </context-param>
         <context-param>  
            <param-name>log4jConfiguration</param-name>  
            <param-value>classpath:log4j2.xml</param-value>  
         </context-param>
         <listener>
             <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
        </listener>
         <filter>
             <filter-name>log4jServletFilter</filter-name>
             <filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class>
         </filter>
         <filter-mapping>
             <filter-name>log4jServletFilter</filter-name>
             <url-pattern>/*</url-pattern>
             <dispatcher>REQUEST</dispatcher>
             <dispatcher>FORWARD</dispatcher>
             <dispatcher>INCLUDE</dispatcher>
             <dispatcher>ERROR</dispatcher>
         </filter-mapping>
         <!-- log4j2-end -->
    </web-app>

      4》springmvc-config.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:mvc="http://www.springframework.org/schema/mvc"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        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 ">
        <!--
          springmvc的配置文件:
                          扫描handler对象
                          配置注解的处理器映射器和处理器适配器
                          配置内部资源视图解析器
                          处理不了的静态资源交给tomcat
         -->
       
       <context:component-scan base-package="com.login.web.controller"/>
       
       <mvc:annotation-driven/>
     
       <bean id="viewResolver" 
             class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
             p:prefix="/WEB-INF/content/" p:suffix=".jsp"/>
             
       <mvc:default-servlet-handler/>
       
    </beans> 

      5》applicationContext-dao.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" 
        xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        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/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
                            http://mybatis.org/schema/mybatis-spring 
                            http://mybatis.org/schema/mybatis-spring.xsd ">
        <!-- 
           spring 整合 mybatis 的配置:
                     配置数据库连接池
                     配置sqlSessionFactory
                     配置扫描器
                     配置扫描所有的service类
         -->
         
         <!-- 加载db.properties文件 -->
         <context:property-placeholder location="classpath:db.properties"/>
         
         <!-- 配置数据库连接池 -->
         <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
             <property name="driverClassName" value="${jdbc_driverClassName}"/>
             <property name="url" value="${jdbc_url}"/>
             <property name="username" value="${jdbc_username}"/>
             <property name="password" value="${jdbc_password}"/>
         </bean>
     
         <!-- 配置sqlSessionFactory -->
         <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 数据库连接池 -->
             <property name="dataSource" ref="dataSource"/>
             <!-- mybatis的配置文件 -->
             <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/>
            <!-- mapper文件 -->
             <property name="mapperLocations">
             <!--加载所有的mapper文件  -->
              <list>
                  <!-- 或者 <value>classpath:mybatis/mappers/*.xml</value> -->
                  <value>classpath:mybatis/mappers/IUserMapper.xml</value>
              </list>
             </property>    
         </bean>
     
         <!-- 配置mapper扫描器 -->
         <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
            <property name="basePackage" value="com.login.dao"/>
         </bean>
         
         <!--扫描所有的service作为spring bean -->
         <context:component-scan base-package="com.login.service"/>
    </beans>

      6》applicationContext-tx.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" 
        xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        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/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
                            http://mybatis.org/schema/mybatis-spring 
                            http://mybatis.org/schema/mybatis-spring.xsd 
                            http://www.springframework.org/schema/aop 
                            http://www.springframework.org/schema/aop/spring-aop.xsd ">
        <!-- 配置spring的事务
                  mybatis采用的是spring中的jdbc中的事务管理(配置事务管理器)
                  事务增强
                  aop切面
          -->
      <!--事务管理  -->
      <bean id="tx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
         <property name="dataSource" ref="dataSource"></property>
      </bean>
    
      <!-- 增强 -->
      <tx:advice id="tx_advice" transaction-manager="tx" >
        <tx:attributes>
            <!-- 事务传播规则 -->
             <tx:method name="save*" propagation="REQUIRED"/>
             <tx:method name="add*" propagation="REQUIRED"/>
             <tx:method name="delete*" propagation="REQUIRED"/>
             <tx:method name="update*" propagation="REQUIRED"/>
             <tx:method name="do*" propagation="REQUIRED"/>
             
             <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
             <tx:method name="list*" propagation="SUPPORTS" read-only="true"/>
             <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
             <tx:method name="query*" propagation="SUPPORTS" read-only="true"/>
             <tx:method name="count*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
      </tx:advice>
      
      <!-- Aop 切面 
           proxy-target-class="false"  是默认的 =====》 默认使用jdk动态代理 基于接口
           proxy-target-class="true"   =============》使用cglib动态代理 基于类
      -->
      <aop:config  proxy-target-class="false">
        <aop:advisor advice-ref="tx_advice" pointcut="execution(* com.login.service.*Service.*(..) )"/>
      </aop:config>
      
    </beans>

      7》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>
      <settings>
         <!--  配置mybatis的日志  -->
         <setting name="logImpl" value="LOG4J2"/>
         <!--开启延迟加载  -->
         <setting name="lazyLoadingEnabled" value="true"/>
         <!--设置不要积极去加载  -->
         <setting name="aggressiveLazyLoading" value="false"/>
         <!--延迟加载的触发方法  -->
         <setting name="lazyLoadTriggerMethods" value="clone"/>
      </settings>
      <!-- 别名 -->
      <typeAliases>
          <package name="com.login.dao"/>
      </typeAliases>
    </configuration>

      8》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">
    
    <mapper namespace="com.login.dao.IUserMapper">
      
      <select id="getUserByUsername" parameterType="map"  resultType="com.login.entity.User">
          SELECT * FROM user WHERE username = #{username} and password= #{password}
      </select>
    </mapper>

      9》db.properties

    jdbc_driverClassName=com.mysql.jdbc.Driver
    jdbc_url=jdbc:mysql://localhost:3306/db_ssm
    jdbc_username=root
    jdbc_password=root

      10》log4j2.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!-- log4j2使用说明(create By SeanXiao    ):
    使用方式如下:
    private static final Logger logger = LogManager.getLogger(实际类名.class.getName());
    
    2、日志说明:
    (1)请根据实际情况配置各项参数
    (2)需要注意日志文件备份数和日志文件大小,注意预留目录空间
    (3)实际部署的时候backupFilePatch变量需要修改成linux目录
     -->
    <configuration status="OFF">
        <Properties>
            <Property name="fileName">front.log</Property>
            <Property name="backupFilePatch">C:/Users/lfy/Desktop/work/temp/log/</Property>
          </Properties>
        <!--先定义所有的appender-->
        <appenders>
            <!--这个输出控制台的配置-->
            <Console name="Console" target="SYSTEM_OUT">
                 <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
                <ThresholdFilter level="trace" onMatch="ACCEPT" onMismatch="DENY" />
                <!--这个都知道是输出日志的格式-->
                <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n" />
            </Console>
            
            <!--这个会打印出所有的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
            <RollingFile name="RollingFile" fileName="${backupFilePatch}${fileName}"
                filePattern="${backupFilePatch}$${date:yyyy-MM}/app-%d{yyyyMMddHHmmssSSS}.log.gz">
                <PatternLayout
                    pattern="%d{yyyy.MM.dd 'at' HH:mm:ss.SSS z} %-5level %class{36} %L %M - %msg%xEx%n" />
                
                <!-- 日志文件大小 -->
                <SizeBasedTriggeringPolicy size="20MB" />
                <!-- 最多保留文件数 -->
                <DefaultRolloverStrategy max="20"/>
            </RollingFile>
        </appenders>
        
        <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效-->
        <loggers>
            <!--建立一个默认的root的logger-->
            <Logger name="com.login.service" level="trace" additivity="true">
                <AppenderRef ref="RollingFile" />
            </Logger>
            <Root level="info">
                <AppenderRef ref="Console" />
            </Root>
        </loggers>
    </configuration>

     11》Controller

    package com.login.web.controller;
    
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.servlet.ModelAndView;
    import com.login.entity.User;
    import com.login.service.IUserService;
    
    @Controller
    @RequestMapping("/UserController")
    public class UserController {
        
        private static final Logger logger = LogManager.getLogger(UserController.class.getName());
        
        @Autowired
        private IUserService service;
        
        /**
         * redirect page
         * @return
         */
        @RequestMapping(path="/loginForm")
        public String loginForm() {
            return "loginForm";
        }
        
        @RequestMapping(path="/login")
        public ModelAndView login(String username,String password,ModelAndView mv) {
            
            User user = service.login(username, password);
            
            if(user != null){
                
                logger.info(user);
                
                mv.addObject("user", user);
                mv.setViewName("success");
            }else{
                mv.addObject("message", "登录名或密码错误,请重新输入!");
                mv.setViewName("loginForm");
            }
            return mv;
        }
    }

      12》Service

    package com.login.service.impl;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import com.login.dao.IUserMapper;
    import com.login.entity.User;
    import com.login.service.IUserService;
    
    @Service
    public class UserServiceImpl implements IUserService {
    
        @Autowired
        private IUserMapper mapper;
        
        @Override
        public User login(String username, String password) {
            
            return  mapper.getUserByUsername(username,password);
        }
    }

      13》DAO

    package com.login.dao;
    
    import org.apache.ibatis.annotations.Param;
    
    import com.login.entity.User;
    
    public interface IUserMapper {
        
      User getUserByUsername(@Param("username") String username,@Param("password") String password);
    }

      14》Entity

    package com.login.entity;
    
    import java.io.Serializable;
    
    public class User implements Serializable {
    
        private static final long serialVersionUID = 1L;
        
        private String username;
        private String password;
        
        public User() {
            super();
        }
        
        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        
        @Override
        public String toString() {
            return "User=[username="+username+",password="+password+"]";
        }
    }
  • 相关阅读:
    tp5出现“continue“ targeting switch is equivalent to “break“. Did you mean to use “continue 2“?错误解决方法
    composer报错Installation failed, reverting ./composer.json to its original content
    bootstrapTable自增序列号
    Linux向github添加公钥
    Git 提示fatal: remote origin already exists 错误解决办法
    bootstrapTable自定义模板
    tp5报错strpos(): Nonstring needles will be interpreted as strings in the future. Use an explicit chr() call to preserve the cu
    vim 操作指令
    中国历史纪年简表
    在VBA中使用Word格式
  • 原文地址:https://www.cnblogs.com/ZeroMZ/p/11428843.html
Copyright © 2020-2023  润新知