记录: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-->
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定义了异常的统一处理机制,其工作原理是:
添加一个类 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>
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>
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>
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>
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-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>
十二、贴个例子
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;
}
}
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);
} }
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);
}
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>
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;
}
}
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>
完。
好文:http://elf8848.iteye.com/blog/875830
记录:springmvc + mybatis + maven 搭建配置流程的更多相关文章
- SSM Spring+SpringMVC+mybatis+maven+mysql环境搭建
SSM Spring+SpringMVC+mybatis+maven环境搭建 1.首先右键点击项目区空白处,选择new->other..在弹出框中输入maven,选择Maven Project. ...
- Spring+SpringMVC+Mybatis+MAVEN+Eclipse+项目完整环境搭建
1.新建一个Maven项目,创建父项目. 2.创建子项目模块 3.创建javaWeb项目 4.创建后的项目目录结构 5.Maven文件配置 parent父项目pom.xml文件配置 <?xml ...
- Spring+SpringMVC+MyBatis+Maven框架整合
本文记录了Spring+SpringMVC+MyBatis+Maven框架整合的记录,主要记录以下几点 一.Maven需要引入的jar包 二.Spring与SpringMVC的配置分离 三.Sprin ...
- 学习笔记_J2EE_SSM_01_spring+springMVC+Mybatis整合_XML配置示例
spring+springMVC+Mybatis整合_XML配置示例 1.概述 spring+springMVC+Mybatis整合 XML配置方式 1.1 测试环境说明 名称 版本 备注 操作系统 ...
- (转)springMVC+mybatis+ehcache详细配置
一. Mybatis+Ehcache配置 为了提高MyBatis的性能,有时候我们需要加入缓存支持,目前用的比较多的缓存莫过于ehcache缓存了,ehcache性能强大,而且位各种应用都提供了解决方 ...
- 转载-Linux下svn搭建配置流程
Linux下svn搭建配置流程 一. 源文件编译安装.源文件共两个,为: 1. 下载subversion源文件 subversion-1.6.1.tar.gz http://d136 ...
- IntelliJ IDEA下Maven SpringMVC+Mybatis入门搭建例子
很久之前写了一篇SSH搭建例子,由于工作原因已经转到SpringMVC+Mybatis,就以之前SSH实现简单登陆的例子,总结看看SpringMVC+Mybatis怎么实现. Spring一开始是轻量 ...
- Maven 搭建 SSM框架——Spring+SpringMVC+Mybatis的搭建教程
一:概述 SSM框架在项目开发中经常使用到,相比于SSH框架,它在仅几年的开发中运用的更加广泛. Spring作为一个轻量级的框架,有很多的拓展功能,最主要的我们一般项目使用的就是IOC和AOP.Sp ...
- SSM框架——Spring+SpringMVC+Mybatis的搭建
1.基本概念 1.1.Spring Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One ...
随机推荐
- “全栈2019”Java多线程第二十章:同步方法产生死锁的例子
难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java多 ...
- 读DEDECMS找后台目录有感
本文作者:红日安全团队——Mochazz 早上看了先知论坛的这篇文章:解决DEDECMS历史难题–找后台目录 不得不说作者思路确实巧妙,作者巧妙的利用了Windows FindFirstFile和织梦 ...
- Dockerfile数据管理
本文介绍Docker内部以及容器间的数据管理,在容器中管理数据主要有两种方式: 数据卷(Volumes) 挂载主机目录(Bind mounts) 数据卷 数据卷是一个可供一个或则多个目录使用的特殊目录 ...
- 再看javascript执行上下文、变量对象
突然看到一篇远在2010年的老文,作者以章节的形式向我们介绍了ECMA-262-3的部分内容,主要涉及到执行上下文.变量对象.作用域.this等语言细节.内容短小而精悍,文风直白而严谨,读完有酣畅淋漓 ...
- gitlab改变服务器ip
一./home/git/gitlab/config/unicorn.rb 其中的ip需要修改,否则unicorn无法启动. 二./home/git/gitlab-shell/config.yml 其中 ...
- celery问题记录
1. 问题:WARNING/MainProcess] /home/jihonghe/.virtualenvs/py3_dj217_env/lib/python3.6/site-packages/bil ...
- openssl生成RSA格式的公私钥,并转为pkcs8格式
第一步:生成私钥,这里我们指定私钥的长度为2048 openssl genrsa -out rsa_private_key.pem 2048 第二步:根据私钥生成对应的公钥: openssl rsa ...
- Vue的实时时间转换Demo
Vue的实时时间转换Demo time.html: <!DOCTYPE html> <html lang="en"> <head> <me ...
- phpredisadmin 莫名其妙错误,打开了无法显示任何数据
一直用的好好的,某天突然只有页面基本框架,redis数据看不到了. 查日志嘛... PHP Fatal error: Allowed memory size of 134217728 bytes e ...
- win10下用Linux搭建python&nodejs开发环境
Win10下用自带Linux系统搭建开发环境 Win10下用自带Linux系统搭建开发环境启用Linux老版本(win10 1709之前):新版本(win10 1709之后)卸载linux老版本新版本 ...