记录:springmvc + mybatis + maven 搭建配置流程

 前言:不会配置 spring mvc,不知道为什么那样配置,也不知道从何下手,那么看这里就对了。

在 IDEA 中搭建 maven + springmvc + mybatis:

一、在 IDEA 中首先创建好一个新的 maven web 项目

可以参考:https://www.cnblogs.com/yuxiaole/p/9223309.html

二、pom 文件

1、添加 pom.xml 中的相关依赖

  需要如下依赖:spring、springmvc、mybatis、oracle、jsp、servlet、访问数据库

  添加 pom 的 oracle 依赖:https://www.cnblogs.com/yuxiaole/p/9479536.html

        <!-- springframework 的相关依赖 start -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>
        <!-- springframework 的相关依赖 end -->

        <!--mybatis-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>

        <!--spring-mybatis 整合-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!--orcale-->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.1.0</version>
        </dependency>

        <!--servlet-->
        <!-- jsp start -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- jsp end -->
        <!--jsp-->
View Code

3、maven 编译之后,需要能读取到 xml 文件,所以在 pom.xml 中 <build></build>加如下代码:

    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
      </resource>
    </resources>

4、maven 编译之后,还需要读取 properties 文件,因为我们一般都将系统配置统一放在 properties 里面

            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>

三、web.xml 文件

使用 Spring MVC,在 web.xml 中配置 DispatcherServlet 是第一步

web.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" xmlns:web="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_2_5.xsd" version="2.5">
  <display-name>sdemo</display-name>

  <!--配置springmvc的分发器-->
  <servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <!--设置mvc的配置文件地址-->
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/spring-mvc.xml</param-value>
    </init-param>
    <!--启动加载的顺序-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <!--“/”: 会拦截所有请求,包括js、jsp、html等-->
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!--配置默认的地址-->
  <!--welcome-file-list元素可以包含一个或多个welcome-file子元素。如果在第一个welcome-file元素中没有找到指定的文件,Web容器就会尝试显示第二个,以此类推。-->
  <welcome-file-list>
    <welcome-file>demoIndex.jsp</welcome-file>
  </welcome-file-list>

</web-app>

还需要在 web.xml 配置读取所有相关的 spring 配置文件

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:spring/system/spring-*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

四、spring-mvc.xml 文件

配置注解扫描文件,注册相关 Bean

配置试图解析器等

<?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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        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">

    <!--会自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdapter两个Bean,这是Spring MVC为@Controller分发请求所必需的,
    并且提供了数据绑定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持读写XML的支持(JAXB)和读写JSON的支持(默认Jackson)等功能-->
    <mvc:annotation-driven />

    <!-- spring 可以自动去扫描 com.demo 下面的包或子包下面的Java文件,
    如果扫描到有Spring的相关注解(@Component @Controller@Service等)的类,则把这些类注册为Spring的bean,
     可以发现这种扫描的粒度有点太大-->
    <!--有一个use-default-filters属性,该属性默认为true,这就意味着会扫描指定包下的全部的标有@Component的类,
    并注册成bean.也就是@Component的子注解@Service,@Reposity等-->
    <!--如果配置了<context:component-scan>那么<context:annotation-config/>标签就可以不用再xml中配置了,因为前者包含了后者-->
    <!--另外<context:component-scan>还提供了两个子标签 <context:include-filter> 和 <context:exclude-filter>-->
    <!--Use-dafault-filters=”false”的情况下:<context:exclude-filter>表示指定的不扫描,<context:include-filter>表示指定的扫描-->
<!--    <context:component-scan base-package="com.yule"/>-->

    <!-- 只需要扫描 com.yule 下的 @Controller 并注册成bean -->
    <context:component-scan base-package="com.yule" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- 视图解析器: 定义JSP文件的位置 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/views/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- 容器默认的DefaultServletHandler处理
    所有静态内容 和 无RequestMapping处理的URL都将经过这里,
    然后将该请求交由WEB应用服务器默认的Servlet进行处理。
    如果不是静态资源的请求和 无RequestMapping处理的URL,才由DispatcherServlet继续进行处理。-->
    <mvc:default-servlet-handler/>

    <!-- 将地址重定向:"/"是访问的path,"/demoCtrl/index"是重定向后的path:
    定义无需Controller的url<->view直接映射-->
    <mvc:view-controller path="/" view-name="redirect:/demoCtrl/index"/>

    <!-- 配置上传文件拦截,设置最大上传文件大小,和最大内存大小 -->
    <bean id="multipartResolver" name="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- set the max upload size100MB  100M=100*1024*1024(B)=104857600 bytes-->
        <property name="maxUploadSize">
            <value>104857600</value>
        </property>
        <property name="maxInMemorySize">
            <value>4096</value>
        </property>
    </bean>

</beans>

以上配置即可启动系统,访问到 ctrl 层(使用@Controller),并且系统启动有默认打开的页面 demoIndex.jsp 。

五、配置 mybatis 相关的配置文件

db.properties

db.driver=oracle.jdbc.OracleDriver
db.datasourceurl=jdbc:oracle:thin:@localhost:1521:ORCL
db.username=testdev
db.password=test1234

mybatis-configuration.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>
        <setting name="defaultStatementTimeout" value="25000" />
        <setting name="logPrefix" value="dao." />
    </settings>
</configuration>

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:p="http://www.springframework.org/schema/p"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
                http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
                http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-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"
       default-lazy-init="true"
       default-autowire="byName">

    <description>整合spring与mybatis</description>
    <!--采用MapperScannerConfigurer,它将会查找类路径下的映射器并自动将它们创建成MapperFactoryBean-->

    <!-- mybatis为spring提供的jar,其配置时不支持正则表达式配置 -->
    <bean id="mySqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.yule.*.*.entity,com.yule.*.*.*.entity"/>
        <property name="configLocation" value="classpath:/spring/system/mybatis-configuration.xml"/>
    </bean>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.yule.*.*.dao,com.yule.*.*.*.dao"/>
        <property name="sqlSessionFactoryBeanName" value="mySqlSessionFactory"/>
    </bean>

    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath*:conf/system/*.properties"/>
    <!-- 扫描注解 -->
    <context:annotation-config/>

    <!-- 需要 commons.dbcp 包 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${db.driver}"/>
        <property name="url" value="${db.datasourceurl}"/>
        <property name="username" value="${db.username}"/>
        <property name="password" value="${db.password}"/>

        <property name="maxActive" value="100"/>
        <property name="maxIdle" value="20"/>
        <property name="maxWait" value="1000"/>
        <property name="defaultAutoCommit" value="true"/>
        <property name="removeAbandoned" value="true"/>
        <property name="removeAbandonedTimeout" value="60"/>
        <property name="validationQuery" value="select count(*) from dual"/>
        <property name="testOnBorrow" value="true"/>
        <property name="testOnReturn" value="true"/>
        <property name="testWhileIdle" value="true"/>
    </bean>

    <!--配置事务-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 支持注解形式 enable transaction annotation support -->
    <tx:annotation-driven transaction-manager="txManager" />

    <!--大字段处理-->
    <!--<bean id="lobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler"></bean>-->

</beans>

六、配置 spring-service 自动注册 service

想在想要访问到 service 层,则可以在 spring-service.xml 中加入以下代码

<!-- 自动注册service -->
    <context:component-scan base-package="com.yule">
        <context:include-filter type="regex" expression=".*\.service\..*" />
    </context:component-scan>

java 代码:不需要写 @Service

七、集成日志 logback

可以参考:https://www.cnblogs.com/yuxiaole/p/9297266.html

pom.xml 中加入依赖

  <!-- slf4j-->
    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.25</version>
    </dependency>    

    <!--logback-->
    <!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.2.3</version>
    </dependency>

logback.xml 配置文件一般放在src/main/resources文件夹,在该文件夹中新建 logback.xml 文件。

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%date{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="rollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>D:/log/demo.log</file>        
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>D:/log/demo.%d{yyyy-MM-dd}.log</fileNamePattern>
        </rollingPolicy>
        <encoder>
            <pattern>%date{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <!-- project default level -->
    <logger name="com.yule" level="INFO" />

    <!--log4jdbc -->
    <logger name="jdbc.sqltiming" level="INFO"/>
    <logger name="dao" level="DEBUG" >
        <appender-ref ref="console" />
    </logger>
    
    <root level="INFO">
        <appender-ref ref="console" />
        <appender-ref ref="rollingFile" />
    </root>
</configuration>

八、配置支持注解 @ResponseBody

  @Responsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中

  该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。

在 pom.xml 文件中加入以下依赖:

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.5</version>
        </dependency>

在 spring-mvc.xml 中配置转化器

    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <!-- 将Jackson2HttpMessageConverter的默认格式化输出设为true -->
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="prettyPrint" value="true"/>
                <!-- 兼容ie -->
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json</value>
                        <value>text/json</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

九、统一处理异常打日志

Spring MVC定义了异常的统一处理机制,其工作原理是:

 不管是应用程序的哪里出现异常,都向上层抛出异常,最后异常被提交到Spring MVC的Dispatcher Servlet中,Dispatcher Servlet在调用系统统一的异常处理器来处理异常。(图片取自https://www.jianshu.com/p/20dd0d28c758)
实现:

添加一个类 MyHandlerExceptionResolver,继承 HandlerExceptionResolver(org.springframework.web.servlet.HandlerExceptionResolver)

实现方法 resolveException,这里先简单实现一下:

/**
 * 统一异常处理,交给DispatcherServlet
 * @author yule
 * @date 2018/9/22 19:01
 */
public class MyHandlerExceptionResolver implements HandlerExceptionResolver {

    private Logger logger = LoggerFactory.getLogger(MyHandlerExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        logger.error("服务器端未知错误", e);
        return new ModelAndView("system/error/error");
    }
}

然后在 spring-mvc.xml 中加入通过bean声明注册到IoC容器

    <!--统一异常处理,记录日志-->
    <bean class="com.yule.system.exception.MyHandlerExceptionResolver" id="myHandlerExceptionResolver"/>

十、测试事务,修改问题

测试事务,发现事务不起作用,即注解 @Transactional 不起作用。

解决方案参考自:https://blog.csdn.net/awp0011/article/details/50735616

所以发现是自己配置的顺序问题导致的,自动注册 service 需要在配置事务之前:

    <!-- 自动注册service 必须在配置事务之上,否则@Transactional不起作用-->
    <context:component-scan base-package="com.yule">
        <context:include-filter type="regex" expression=".*\.service\..*" />
    </context:component-scan>

    <!--配置事务-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="myDataSource"/>
    </bean>
    <!-- 支持注解形式 enable transaction annotation support -->
    <tx:annotation-driven transaction-manager="txManager" />

十一、总结

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>springmvc-mybatis-test</groupId>
    <artifactId>springmvc-mybatis-test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>springmvc-mybatis-test 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.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

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

        <!-- springframework 的相关依赖 start -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>
        <!-- springframework 的相关依赖 end -->

        <!--mybatis-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>

        <!--spring-mybatis 整合-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!--orcale-->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.1.0</version>
        </dependency>

        <!--servlet-->
        <!-- jsp start -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- jsp end -->
        <!--jsp-->

        <!--日志-->
        <!-- slf4j-->
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>

        <!--logback-->
        <!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>

        <!--支持@ResponseBody 返回json-->
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.5</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>springmvc-mybatis-test</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.0.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.7.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.20.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.0</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>

        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
</project>
View Code

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:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        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">

    <!--会自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdapter两个Bean,这是Spring MVC为@Controller分发请求所必需的,
    并且提供了数据绑定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持读写XML的支持(JAXB)和读写JSON的支持(默认Jackson)等功能-->
    <mvc:annotation-driven />

    <!-- 只需要扫描 com.yule 下的 @Controller 并注册成bean -->
    <context:component-scan base-package="com.yule" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
    </context:component-scan>

    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <!-- 将Jackson2HttpMessageConverter的默认格式化输出设为true -->
            <!--支持@ResponseBody 返回json-->
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="prettyPrint" value="true"/>
                <!-- 兼容ie -->
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json</value>
                        <value>text/json</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!-- 视图解析器: 定义JSP文件的位置 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/views/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- 容器默认的DefaultServletHandler处理
    所有静态内容 和 无RequestMapping处理的URL都将经过这里,
    然后将该请求交由WEB应用服务器默认的Servlet进行处理。
    如果不是静态资源的请求和 无RequestMapping处理的URL,才由DispatcherServlet继续进行处理。-->
    <mvc:default-servlet-handler/>

    <!-- 将地址重定向:"/"是访问的path,"/demoCtrl/index"是重定向后的path:
    定义无需Controller的url<->view直接映射-->
    <!--<mvc:view-controller path="/" view-name="redirect:/demoCtrl/index"/>-->

    <!--统一异常处理,记录日志-->
    <bean class="com.yule.system.exception.MyHandlerExceptionResolver" id="myHandlerExceptionResolver"/>

</beans>
View Code

mybatis-datasource.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:jee="http://www.springframework.org/schema/jee"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
                http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
                http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-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"
       default-lazy-init="true"
       default-autowire="byName">

    <description>配置mybatis数据源</description>

    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath*:conf/system/*.properties"/>

    <!-- 需要 commons.dbcp 包 -->
    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${db.driver}"/>
        <property name="url" value="${db.datasourceurl}"/>
        <property name="username" value="${db.username}"/>
        <property name="password" value="${db.password}"/>

        <property name="maxActive" value="100"/>
        <property name="maxIdle" value="20"/>
        <property name="maxWait" value="1000"/>
        <property name="defaultAutoCommit" value="true"/>
        <property name="removeAbandoned" value="true"/>
        <property name="removeAbandonedTimeout" value="60"/>
        <property name="validationQuery" value="select count(*) from dual"/>
        <property name="testOnBorrow" value="true"/>
        <property name="testOnReturn" value="true"/>
        <property name="testWhileIdle" value="true"/>
    </bean>

    <!--大字段处理-->
    <!--<bean id="lobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler"></bean>-->

</beans>
View Code

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:p="http://www.springframework.org/schema/p"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
                http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
                http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-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"
       default-lazy-init="true"
       default-autowire="byName">

    <description>整合spring与mybatis</description>
    <!--采用MapperScannerConfigurer,它将会查找类路径下的映射器并自动将它们创建成MapperFactoryBean-->

    <!-- mybatis为spring提供的jar,其配置时不支持正则表达式配置 -->
    <bean id="mySqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="myDataSource"/>
        <property name="typeAliasesPackage" value="com.yule.*.entity,com.yule.*.*.entity,com.yule.*.*.*.entity"/>
        <property name="configLocation" value="classpath:/mybatis/system/mybatis-configuration.xml"/>
    </bean>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.yule.*.dao,com.yule.*.*.dao,com.yule.*.*.*.dao"/>
        <property name="sqlSessionFactoryBeanName" value="mySqlSessionFactory"/>
    </bean>

</beans>
View Code

mybatis-configuration.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>
        <setting name="defaultStatementTimeout" value="25000" />
        <setting name="logPrefix" value="dao." />
    </settings>
</configuration>
View Code

spring-service.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:jee="http://www.springframework.org/schema/jee"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
                http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
                http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-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"
       default-lazy-init="true"
       default-autowire="byName">

    <description>spring service 层的自动注册和事务配置</description>
    <!--采用MapperScannerConfigurer,它将会查找类路径下的映射器并自动将它们创建成MapperFactoryBean-->

    <!-- 自动注册service 必须在配置事务之上,否则@Transactional不起作用-->
    <context:component-scan base-package="com.yule">
        <context:include-filter type="regex" expression=".*\.service\..*" />
    </context:component-scan>

    <!--配置事务-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="myDataSource"/>
    </bean>
    <!-- 支持注解形式 enable transaction annotation support -->
    <tx:annotation-driven transaction-manager="txManager" />

</beans>
View Code

 十二、贴个例子

ctrl 层

package com.yule.component.dbcomponent.web.ctrl;

import com.yule.component.dbcomponent.entity.UserTables;
import com.yule.component.dbcomponent.service.DbComponentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author yule
 * @date 2018/9/22 15:57
 */
@Controller
@RequestMapping("/dbComponentCtrl")
public class DbComponentCtrl {
    @Autowired
    private DbComponentService dbComponentService;

    @RequestMapping("/index")
    public String index(){
        return "yule/component/dbcomponent/dbComponent";
    }

    /**
     * 查询所有表名
     * @return
     */
    @RequestMapping("/selectUserTablesNameList")
    @ResponseBody
    public List<UserTables> selectUserTablesNameList(){
        List<UserTables> userTablesList = this.dbComponentService.selectUserTablesNameList();
        return userTablesList;
    }
}
View Code

service 层

package com.yule.component.dbcomponent.service.impl;

import com.yule.component.dbcomponent.dao.UserColCommentsDao;
import com.yule.component.dbcomponent.dao.UserTablesDao;
import com.yule.component.dbcomponent.entity.UserColComments;
import com.yule.component.dbcomponent.entity.UserTables;
import com.yule.component.dbcomponent.service.DbComponentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author yule
 * @date 2018/9/22 15:57
 */
public class DbComponentServiceImpl implements DbComponentService {
    @Autowired
    private UserTablesDao userTablesDao;
    @Autowired
    private UserColCommentsDao userColCommentsDao;

    @Transactional
    @Override
    public List<UserTables> selectUserTablesNameList() {
        return this.userTablesDao.selectUserTablesNameList();
    }

    @Override
    public List<UserColComments> selectUserColCommentsListByTbName(String tableName){
        return this.userColCommentsDao.selectUserColCommentsListByTbName(tableName);
    }

}
View Code

dao 接口 层

package com.yule.component.dbcomponent.dao;

import com.yule.component.dbcomponent.entity.UserColComments;

import java.util.List;

/**
 * @author yule
 * @date 2018/9/22 15:37
 */
public interface UserColCommentsDao {
    /**
     * 查询某个表下的所有字段
     * @param tableName
     * @return
     */
    List<UserColComments> selectUserColCommentsListByTbName(String tableName);
}
View Code

dao 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.yule.component.dbcomponent.dao.UserColCommentsDao">

    <!--查询某个表下的所有字段-->
    <select id="selectUserColCommentsListByTbName" resultType="com.yule.component.dbcomponent.entity.UserColComments">
      select t.table_name tableName,
        t.column_name columnName,
        comments
      from user_col_comments t
     where upper(t.TABLE_NAME) = upper(#{tableName})
    </select>

</mapper>
View Code

entity

package com.yule.component.dbcomponent.entity;

/**
 * @author yule
 * @date 2018/9/22 15:38
 */
public class UserColComments {
    /**
     * 列名所属表
     */
    private String tableName;
    /**
     * 列字段名
     */
    private String columnName;
    /**
     * 列注释
     */
    private String comments;

    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public String getColumnName() {
        return columnName;
    }

    public void setColumnName(String columnName) {
        this.columnName = columnName;
    }

    public String getComments() {
        return comments;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }
}
View Code

jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>数据库单表查询组件</title>
</head>
<body>

<h1>水电费水电费水电费</h1>

</body>
</html>
View Code

 

完。

 

好文:http://elf8848.iteye.com/blog/875830

 

posted @ 2018-09-22 21:34  取个名字吧  阅读(352)  评论(0编辑  收藏  举报