美文网首页
Idea中SpringMVC整合Mybatis+log4j日志

Idea中SpringMVC整合Mybatis+log4j日志

作者: 一叶知秋_zgx | 来源:发表于2018-10-26 17:03 被阅读0次
    以下是我idea项目中的分层结构
    image.png

    SpringMVC:

    SpringMVC是一spring的一个子框架,它是一种基于Java,实现了Web MVC设计模式,请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,MVC分为model view controller 三层,将Web层进行职责解耦。基于请求驱动指的就是使用请求-响应模型,它帮助我们让我们减下了代码量,比structs2的代码量小。

    Mybatis:

    mybatis是一种半自动化的ORM(Object Relational Mapping,简称ORM,或O/RM,或O/R mapping)框架,它的作用是使得我们在与数据库交互的时候变得简单,我们可以将sql语句几种卸载xml里面,以实现Dao层的接口来进行数据查询,所以要想更简单的编码,我们需要对SSM(Spring,SpringMVC,Mybatis)来进行配置,配置过后就相当于做好了第一步,把框架搭好。

    pom.xml

    <?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.xingxuecn.limit</groupId>
        <artifactId>limit-kris</artifactId>
        <version>1.0-SNAPSHOT</version>
        <packaging>war</packaging>
    
        <properties>
            <jackson-version>2.9.6</jackson-version>
            <spring.version>5.1.0.RELEASE</spring.version>
            <mybatis.version>3.4.6</mybatis.version>
            <slf4j.version>1.6.6</slf4j.version>
            <log4j.version>1.2.12</log4j.version>
            <mysql.version>5.1.29</mysql.version>
        </properties>
    
        <dependencies>
            <!-- 添加Spring依赖 -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</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-context-support</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-aspects</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-web</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!--spring单元测试依赖 -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>${spring.version}</version>
                <scope>test</scope>
            </dependency>
    
            <!-- spring webmvc相关jar -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <!-- mysql驱动包 -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
            </dependency>
    
            <!-- alibaba data source 相关jar包-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>0.2.23</version>
            </dependency>
    
            <!-- alibaba fastjson 格式化对 -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.1.41</version>
            </dependency>
    
            <!-- logback 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>ch.qos.logback</groupId>
                <artifactId>logback-classic</artifactId>
                <version>1.1.2</version>
            </dependency>
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-core</artifactId>
                <version>1.1.2</version>
            </dependency>
            <dependency>
                <groupId>org.logback-extensions</groupId>
                <artifactId>logback-ext-spring</artifactId>
                <version>0.1.1</version>
            </dependency>
            <!--mybatis依赖 -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.6</version>
            </dependency>
    
            <!-- mybatis/spring包 -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>1.3.2</version>
            </dependency>
    
            <!-- 添加servlet3.0核心包 -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>3.0.1</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>javax.servlet.jsp-api</artifactId>
                <version>2.3.2-b01</version>
            </dependency>
            <!-- jstl -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>1.2</version>
            </dependency>
            <!--单元测试依赖 -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>3.8.1</version>
                <scope>test</scope>
            </dependency>
            <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.10.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.10.0</version>
        </dependency>
    
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-web</artifactId>
            <version>2.11.1</version>
        </dependency>
    
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.1</version>
    </dependency>
    
    
        </dependencies>
    
        <build>
            <finalName>logistics</finalName>
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
                <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
            </resources>
            <plugins>
    
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <groupId>org.apache.maven.plugins</groupId>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                        <encoding>UTF-8</encoding>
                        <optimize>true</optimize>
                    </configuration>
                </plugin>
    
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.5</version>
                    <configuration>
                        <skip>true</skip>
                    </configuration>
                </plugin>
    
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>build-helper-maven-plugin</artifactId>
                    <version>1.8</version>
                    <executions>
                        <execution>
                            <id>add-resource</id>
                            <phase>generate-resources</phase>
                            <goals>
                                <goal>add-resource</goal>
                            </goals>
                            <configuration>
                                <resources>
                                    <resource>
                                        <directory>src/main/java</directory>
                                        <includes>
                                            <include>**/*.xml</include>
                                        </includes>
                                    </resource>
                                </resources>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
    
    
        </build>
    </project>
    

    log4j2.xml

    <?xml version="1.0" encoding="UTF-8"?>
    
    <!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
    
    <!--Configuration后面的status,这个用于设置log4j2自身内部的信息输出,可以不设置,当设置成trace时,你会看到log4j2内部各种详细输出-->
    
    <!--monitorInterval:Log4j能够自动检测修改配置 文件和重新配置本身,设置间隔秒数-->
    
    <configuration status="WARN" monitorInterval="30">
    
        <!--先定义所有的appender-->
    
        <appenders>
    
            <!--这个输出控制台的配置-->
    
            <console name="Console" target="SYSTEM_OUT">
    
                <!--输出日志的格式-->
    
                <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
    
            </console>
    
            <!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用-->
    
            <File name="log" fileName="e:/log/test.log" append="false">
    
                <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
    
            </File>
    
            <!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
    
            <RollingFile name="RollingFileInfo" fileName="e:/logs/info.log"
    
                         filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
    
                <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
    
                <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
    
                <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
    
                <Policies>
    
                    <TimeBasedTriggeringPolicy/>
    
                    <SizeBasedTriggeringPolicy size="100 MB"/>
    
                </Policies>
    
            </RollingFile>
    
            <RollingFile name="RollingFileWarn" fileName="e:/logs/warn.log"
    
                         filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
    
                <ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/>
    
                <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
    
                <Policies>
    
                    <TimeBasedTriggeringPolicy/>
    
                    <SizeBasedTriggeringPolicy size="100 MB"/>
    
                </Policies>
    
                <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 -->
    
                <DefaultRolloverStrategy max="20"/>
    
            </RollingFile>
    
            <RollingFile name="RollingFileError" fileName="e:/logs/error.log"
    
                         filePattern="${sys:user.home}/logs/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log">
    
                <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
    
                <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
    
                <Policies>
    
                    <TimeBasedTriggeringPolicy/>
    
                    <SizeBasedTriggeringPolicy size="100 MB"/>
    
                </Policies>
    
            </RollingFile>
    
        </appenders>
    
        <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效-->
    
        <loggers>
    
            <!--过滤掉spring和mybatis的一些无用的DEBUG信息-->
    
            <logger name="org.springframework" level="INFO"></logger>
    
            <logger name="org.mybatis" level="INFO"></logger>
    
            <root level="all">
    
                <appender-ref ref="Console"/>
    
                <appender-ref ref="RollingFileInfo"/>
    
                <appender-ref ref="RollingFileWarn"/>
    
                <appender-ref ref="RollingFileError"/>
    
            </root>
    
        </loggers>
    
    </configuration>
    
    

    jdbc.properties

    jdbc_driverClassName = com.mysql.jdbc.Driver
    jdbc_url=jdbc:mysql://localhost:3306/invite?useUnicode=true&characterEncoding=utf8
    jdbc_username=root
    jdbc_password=root
    

    driverClassName 数据库连接需要加载驱动,所以连接的驱动是com.mysql.jdbc.Driver。
    url表示数据库的连接地址加上数据库名字,后面跟的是指定字符串的编码并且编码设为utf-8。
    username和password便是数据库的账号和密码。

    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:aop="http://www.springframework.org/schema/aop"
           xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
    
        <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations" value="classpath:jdbc.properties"/>
        </bean>
        <!-- 3.配置数据源 ,使用的alibba的数据库-->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
            <!-- 基本属性 url、user、password -->
            <property name="driverClassName" value="${jdbc_driverClassName}"/>
            <property name="url" value="${jdbc_url}"/>
            <property name="username" value="${jdbc_username}"/>
            <property name="password" value="${jdbc_password}"/>
    
            <!-- 配置初始化大小、最小、最大 -->
            <property name="initialSize" value="10"/>
            <property name="minIdle" value="10"/>
            <property name="maxActive" value="50"/>
    
            <!-- 配置获取连接等待超时的时间 -->
            <property name="maxWait" value="60000"/>
            <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
            <property name="timeBetweenEvictionRunsMillis" value="60000" />
    
            <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
            <property name="minEvictableIdleTimeMillis" value="300000" />
    
            <property name="validationQuery" value="SELECT 'x'" />
            <property name="testWhileIdle" value="true" />
            <property name="testOnBorrow" value="false" />
            <property name="testOnReturn" value="false" />
    
            <!-- 打开PSCache,并且指定每个连接上PSCache的大小  如果用Oracle,则把poolPreparedStatements配置为true,mysql可以配置为false。-->
            <property name="poolPreparedStatements" value="false" />
            <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
    
            <!-- 配置监控统计拦截的filters -->
            <property name="filters" value="wall,stat" />
        </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/xingxue/mapper/*.xml"></property>
        </bean>
    
    
        <!-- DAO接口所在包名,Spring会自动查找其下的类 ,自动扫描了所有的XxxxMapper.xml对应的mapper接口文件,只要Mapper接口类和Mapper映射文件对应起来就可以了-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.xingxue.dao" />
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
        </bean>
    
    
        <bean id="transactionManager"
              class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource" />
        </bean>
    
        <!--======= 事务配置 End =================== -->
        <!-- 配置基于注解的声明式事务 -->
        <!-- enables scanning for @Transactional annotations -->
        <tx:annotation-driven transaction-manager="transactionManager" />
    
    
    </beans>
    

    web.xml 在WEN-INF下

    <?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>SSM-DEMO</display-name>
    
        <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>
    
    
        <!-- 读取spring配置文件 -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </context-param>
    
    
        <context-param>
            <param-name>log4jConfigLocation</param-name>
            <param-value>classpath:log4j.properties</param-value>
        </context-param>
        <!-- 3000表示 开一条watchdog线程每60秒扫描一下配置文件的变化;这样便于日志存放位置的改变 -->
        <context-param>
            <param-name>log4jRefreshInterval</param-name>
            <param-value>3000</param-value>
        </context-param>
    
    
    
        <!-- 设计路径变量值
        <context-param>
            <param-name>webAppRootKey</param-name>
            <param-value>springmvc.root</param-value>
        </context-param>
        -->
    
        <!-- Spring字符集过滤器 -->
        <filter>
            <filter-name>SpringEncodingFilter</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>SpringEncodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    
        <!-- springMVC核心配置 -->
        <servlet>
            <servlet-name>dispatcherServlet</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <!--spingMVC的配置路径 -->
                <param-value>classpath:applicationContext.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <!-- 拦截设置 -->
        <servlet-mapping>
            <servlet-name>dispatcherServlet</servlet-name>
            <url-pattern>*.do</url-pattern>
        </servlet-mapping>
    
    
        <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
    
    </web-app>
    
    

    spring-mvc.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:p="http://www.springframework.org/schema/p"
           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-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/mvc
                            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    
    
    <!-- 2.扫描的包路径,这里不扫描被@Controller注解的类 --><!--使用<context:component-scan/> 可以不在配置<context:annotation-config/> -->
        <context:component-scan base-package="com.xingxue"/>
    
        <mvc:annotation-driven/>
    
        <!-- Spring MVC视图解析配置-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/pages/" />
            <property name="suffix" value=".jsp" />
        </bean>
    </beans>
    

    其中<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    是表示idea中tomcat没有设置跳转的页面的时候自动跳转到webapp中的index.jsp。
    这里面的<propety name="" value=""/> prefix表示视图跳转问题,在controller中用到ModelAndView方法时,最后return返回跳转的位置,项目中的webapp是根目录,跳转都是从这个路径下开始寻找,suffix表示跳转的jsp文件后缀,
    假如controller中写return new ModelAndView("login"),则最后返回到/webapp/pages/login.jsp。还有一种就是如果是web.xml中配置了拦截器,拦截掉了*.do,就要在return中返回道德login后面加上.do。这是要注意的地方。

    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:p="http://www.springframework.org/schema/p"
           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-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/mvc
                            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    
    
        
    
        <import resource="classpath:spring-mybatis.xml" />
        <import resource="classpath:spring-mvc.xml" />
    
    </beans>
    

    这也是通过别人那拷的代码来跑起的,以便下次查看。

    相关文章

      网友评论

          本文标题:Idea中SpringMVC整合Mybatis+log4j日志

          本文链接:https://www.haomeiwen.com/subject/eeqhtqtx.html