maven构建spring mvc项目 + Mybatis整合

一、新建项目

1、File>New>Other>Maven>Maven Project, 点击Next

  maven构建spring mvc项目 + Mybatis整合_第1张图片


2、选择项目保存路径。然后点击Next。
 
maven构建spring mvc项目 + Mybatis整合_第2张图片

3、选择项目类型,在Artifact Id中选择maven-archetype-webapp,然后点击Next。
maven构建spring mvc项目 + Mybatis整合_第3张图片 


4、Group ID一般写大项目名称。Artifact ID是子项目名称。
例如Spring的web包,Group ID:org.springframework,artifactId:spring-web。
Package是默认给你建一个包,不写也可以。
填完后,点击Finish。
maven构建spring mvc项目 + Mybatis整合_第4张图片


5、建好后的项目结构如下:

maven构建spring mvc项目 + Mybatis整合_第5张图片

 
6、打开cmd命令窗口,cd到项目的跟目录。执行以下语句:
mvn clean eclipse:eclipse

注:
mvn clean     //清理(删除target目录下编译内容)

mvn eclipse:eclipse   //生成Eclipse项目结构


7、选中项目,右击:New>Other>java>Source Folder,点击Next
  maven构建spring mvc项目 + Mybatis整合_第6张图片


8、以下Floder Name必须为src/main/java
  maven构建spring mvc项目 + Mybatis整合_第7张图片


9、现目录结构如下:
 




二、配置文件设置(附部分配置说明)
1、pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>cn.com.abel</groupId>
	<artifactId>springProject</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>springProject Maven Webapp</name>
	<url>http://maven.apache.org</url>
  
    <properties>
		<slf4j.version>1.6.4</slf4j.version>
		<spring.version>3.1.2.RELEASE</spring.version>
		<jdk.version>1.6</jdk.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	
	<dependencies>
	    <dependency>
		    <groupId>junit</groupId>
		    <artifactId>junit</artifactId>
		    <version>3.8.1</version>
		    <scope>test</scope>
	    </dependency>
	    
	    <!-- spring begin -->
	    <dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
   			<groupId>org.springframework</groupId>
   			<artifactId>spring-core</artifactId>
   			<version>${spring.version}</version>
   		</dependency>
   		<dependency>
   			<groupId>org.springframework</groupId>
   			<artifactId>spring-beans</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-aop</artifactId>
   			<version>${spring.version}</version>
   		</dependency>
   		<dependency>
   			<groupId>org.springframework</groupId>
   			<artifactId>spring-tx</artifactId>
   			<version>${spring.version}</version>
   		</dependency>
   		
   		<dependency>
   			<groupId>org.aspectj</groupId>
   			<artifactId>aspectjrt</artifactId>
   			<version>1.6.9</version>
   		</dependency>
   		<dependency>
   			<groupId>org.aspectj</groupId>
   			<artifactId>aspectjweaver</artifactId>
   			<version>1.6.9</version>
   		</dependency>
   		<dependency>
   			<groupId>cglib</groupId>
   			<artifactId>cglib-nodep</artifactId>
   			<version>2.2</version>
   		</dependency>
   		<!-- spring end -->
   		
   		<!-- mybatis begin -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.1.1</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.1.1</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<!-- mybatis end -->
		
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.21</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		
		<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>2.3.19</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.16</version>
		</dependency>
		
	</dependencies>
	
	<build>
		<finalName>springProject</finalName>
		<plugins>
			<!-- jetty插件 -->
			<plugin>
				<groupId>org.mortbay.jetty</groupId>
				<artifactId>maven-jetty-plugin</artifactId>
				<version>6.1.25</version>
			</plugin>
			
			<plugin>
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.3.1</version>
				<configuration>
					<configurationFile>src/main/resources/mybatis-generator.xml</configurationFile>
					<overwrite>true</overwrite>
				</configuration>
			</plugin>
		</plugins>
	</build>
  
</project>

2、web.xl

<?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/web-app_2_5.xsd"
	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>springProject Application</display-name>
  	 
  	 <!-- 指定上下文配置文件 -->
  	 <context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
				 classpath:applicationContext.xml
		</param-value>
	</context-param>
	
	<!-- spring监听器,监听springMvc环境 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<!-- 压入项目路径 -->
	<listener>
	   <listener-class>org.springframework.web.util.WebAppRootListener</listener-class>
	</listener>
  
	 <!-- springMvc前置总控制器,在分发其它的控制器前都要经过这个总控制器 -->
	 <servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring-servlet.xml</param-value>
		</init-param>
		<!-- 启动顺序 -->
		<load-on-startup>1</load-on-startup>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/</url-pattern>
		<!-- 
		<url-pattern>/</url-pattern>  会匹配到/login这样的路径型url,不会匹配到模式为*.jsp这样的后缀型url
		<url-pattern>/*</url-pattern> 会匹配所有url:路径型的和后缀型的url(包括/login,*.jsp,*.js和*.html等)
		 -->
	</servlet-mapping>
	
</web-app>

3、spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
						http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
						http://www.springframework.org/schema/mvc
						http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
						http://www.springframework.org/schema/context 
						http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- 
	自动扫描组件,可以写多个。component-scan 默认扫描的注解类型是 @Component,
	不过,在 @Component语义基础上细化后的 @Repository、 @Service 和 @Controller 
	也同样可以获得 component-scan 的青睐 
	 -->
	<context:component-scan base-package="cn.com.abel.springProject.**"/>
<!--	<context:component-scan base-package="cn.com.abel.springProject.controller" />-->
	
	<!--  
	<mvc:annotation-driven /> 是一种简写形式,完全可以手动配置替代这种简写形式,会自动注册
	DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean,
	是spring MVC为@Controllers分发请求所必须的。 
	 -->
	<mvc:annotation-driven />
	
	<!-- 
	配置js,css等静态文件直接映射到对应的文件夹,不被DispatcherServlet处理
	若将以下改为:<mvc:default-servlet-handler />则使用默认的Servlet来响应静态文件
	 -->
    <mvc:resources mapping="/resources/**" location="/resources/" />
	
	<!-- 
	拦截器,本例中以下使用的方案是:拦截所有url。
	另一种是:拦截匹配的URL,以下例子是当访问/user/*被BaseInterceptor拦截
	<mvc:interceptors >
	  <mvc:interceptor>
		  <mvc:mapping path="/user/*" />
		  <bean class="cn.com.abel.springProject.interceptors.BaseInterceptor"></bean>
	  </mvc:interceptor>
  </mvc:interceptors>
	 -->
	<mvc:interceptors>
		<bean class="cn.com.abel.springProject.interceptors.BaseInterceptor" />
	</mvc:interceptors>
	
<!--	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />-->
	
	<!-- FreeMarker begin -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"
		lazy-init="false">
		<property name="contentType" value="text/html; charset=UTF-8" />
		<property name="exposeSpringMacroHelpers" value="true" />
		<property name="requestContextAttribute" value="rc" />
		<property name="prefix" value="" />
		<property name="suffix" value=".html" />
	</bean>
	<bean id="freemarkerConfig"
		class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
		<property name="freemarkerVariables">
			<map>
				<entry key="xml_escape" value-ref="fmXmlEscape" />
				<entry key="html_escape" value-ref="fmHtmlEscape" />
			</map>
		</property>
		<property name="templateLoaderPaths">
			<list>
				<value>/WEB-INF/views/</value>
			</list>
		</property>
		<property name="freemarkerSettings">
			<props>
				<prop key="tag_syntax">auto_detect</prop>
				<prop key="template_update_delay">0</prop>
				<prop key="defaultEncoding">UTF-8</prop>
				<prop key="url_escaping_charset">UTF-8</prop>
				<prop key="locale">zh_CN</prop>
				<prop key="boolean_format">true,false</prop>
				<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
				<prop key="date_format">yyyy-MM-dd</prop>
				<prop key="time_format">HH:mm:ss</prop>
				<prop key="number_format">0.##</prop>
				<prop key="whitespace_stripping">true</prop>
				<prop key="classic_compatible">true</prop>
			</props>
		</property>
		<property name="defaultEncoding" value="utf-8" />
	</bean>
	
	<bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape" />
	<bean id="fmHtmlEscape" class="freemarker.template.utility.HtmlEscape" />
	<!-- FreeMarker end -->

</beans>	

4、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:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/jdbc
 	http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
 	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
	
	
    <!-- 加载数据源配置文件 -->
    <bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <!-- 标准配置 -->
                <value>classpath:/jdbc.properties</value>
            </list>
        </property>
    </bean>
	
	<!-- 配置数据源 -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${ad.jdbc.driverClassName}" />
		<property name="url" value="${ad.jdbc.url}" />
		<property name="username" value="${ad.jdbc.username}" />
		<property name="password" value="${ad.jdbc.password}" />
	</bean>
	
	<!-- 配置事务管理器 -->  
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- configLocation:用于指定Mybatis的配置文件位置 -->
		<property name="configLocation" value="classpath:mybatis-config.xml" />
	</bean>
	
<!--	<context:component-scan base-package="cn.com.abel.springProject.**"/>-->
    
    <!-- 
         注册 
    AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、
	PersistenceAnnotationBeanPostProcessor、RequiredAnnotationBeanPostProcessor
	四个bean容器
     -->
    <context:annotation-config />
	
	
    <tx:annotation-driven />
	
	<!-- 
	自动扫描和注册Mapper接口
	basePackage是用来指定Mapper接口文件所在的基包,
	在这个基包或其所有子包下面的Mapper接口都将被搜索到。
	多个基包之间可以使用逗号或者分号进行分隔
	 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="
		  cn.com.abel.springProject.mapper,
		  cn.com.abel.springProject.dao
		" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
	</bean>

</beans>


5、mybatis-generator.xml (MyBatis自动生成映射文件:model、dao)

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE generatorConfiguration  
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"  
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
	<!-- classPathEntry:数据库的JDBC驱动,换成你自己的驱动位置 -->  
	<classPathEntry location="E:/m2/repository/mysql/mysql-connector-java/5.1.13/mysql-connector-java-5.1.13.jar" />

	<context id="generatorTables" targetRuntime="MyBatis3">

		<plugin type="org.mybatis.generator.plugins.MapperConfigPlugin">
		<property name="fileName" value="mybatis-config.xml"/>
		<property name="targetPackage" value="/"/>
		<property name="targetProject" value="src/main/resources"/>
		</plugin>
		
		<!-- 此处是将Example改名为Criteria 当然 想改成什么都行 -->
		<plugin type="org.mybatis.generator.plugins.RenameExampleClassPlugin">
		<property name="searchString" value="Example"/>
		<property name="replaceString" value="Criteria"/>
		</plugin>

		<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>

		<!-- commentGenerator 去除自动生成的注释  -->
		<commentGenerator>
		<property name="suppressDate" value="true" />
		</commentGenerator>

		<!-- jdbcConnection是指定的jdbc的连接信息; -->
		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
		connectionURL="jdbc:mysql://localhost/can_mall" userId="root"
		password="123">
		</jdbcConnection>

		<!-- 
		默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer true,
		把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal 
		-->
		<javaTypeResolver>
		<property name="forceBigDecimals" value="false" />
		</javaTypeResolver>

		<!-- javaModelGenerator是模型的生成信息,这里将指定这些Java model类的生成路径; -->
		<javaModelGenerator targetPackage="cn.com.abel.springProject.model"
		targetProject="src/main/java">
		<property name="enableSubPackages" value="true" />
		<property name="trimStrings" value="true" />
		</javaModelGenerator>

		<!-- sqlMapGenerator是mybatis 的sqlMapper XML文件的生成信息,包括生成路径等; -->
		<sqlMapGenerator targetPackage="cn.com.abel.springProject.dao"
		targetProject="src/main/resources">
		<property name="enableSubPackages" value="true" />
		</sqlMapGenerator>

		<!-- javaClientGenerator是应用接口的生成信息; -->
		<javaClientGenerator type="XMLMAPPER"
		targetPackage="cn.com.abel.springProject.dao" targetProject="src/main/java">
		<property name="enableSubPackages" value="true" />
		</javaClientGenerator>


		<!-- table是用户指定的被生成相关信息的表,它必须在指定的jdbc连接中已经被建立。 -->
		<table tableName="testTabel" domainObjectName="TestModel" >
			<!-- 返回新增记录ID值 -->
			<generatedKey column="ID" sqlStatement="MySql" identity="true"/>
			<columnOverride column="IS_NEW" javaType="Boolean"/>
		</table>

	</context>
</generatorConfiguration>  

6、IndexController.java

package cn.com.abel.springProject.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.com.abel.springProject.dao.TestModelMapper;
import cn.com.abel.springProject.model.TestModel;

/**
TestModelMapper与TestModel为Mybatis自动生成的dao和model
*/
@Controller
@RequestMapping("")
public class IndexController {
	
	@Autowired
	private TestModelMapper testDao;
	
	@RequestMapping
	public String index(ModelMap model) {
		
		//从testTable中查找ID为1的记录
		TestModel testModel = testDao.selectByPrimaryKey(1L);

		model.addAttribute("testModel", testModel);
		model.addAttribute("hello", "hfffello spring mvc");
		return "index";
	}

}

项目源码下载地址

你可能感兴趣的:(maven构建spring mvc项目 + Mybatis整合)