介绍如何使用IntelliJ IDEA创建Spring + SpringMVC + MyBatis项目

了解Maven

  Apache Maven( [ˈmeivən] ),是一个软件(特别是Java软件)项目管理及自动构建工具,可以通过一小段描述信息(配置)来管理项目的构建。   配置pom.xml,通过groupId、artifactId、version三个属性来自动获取指定的jar包,。

创建Maven项目

File -> New Project,创建新项目。

  1. 选择侧栏的Maven
  2. 勾选create from archtype
  3. 选择Maven org.apache.maven.archetype-webapp

点击Next,填写GroupId、ArtifactId和Version

  • GroupId: cn.hbson.web
  • ArtifactId: web-ssm
  • Version: 1.0-SNAPSHOT

点击Next,需要在Properties中添加 archetypeCatalog=internal

  不加这个参数,在maven生成骨架的时候将会非常慢,有时候直接卡住。

archetypeCatalog表示插件使用的archetype元数据,不加这个参数时默认为remote,local,即中央仓库archetype元数据,由于中央 仓库的archetype太多了所以导致很慢,指定internal来表示仅使用内部元数据。

填写Module name

  随意

了解项目目录结构

Web项目结构初识

  基于Java的Web项目,标准的打包方式是WAR。
  与JAR比较,包含更多的内容,比如JSP文件、Servlet、Java类、web.xml配置文件、依赖JAR包、静态web资源(HTML、CSS、JavaScript)等。
  WEB-INF是WAR包的核心。   classes和lib目录都会在运行的时候被加入到Classpath中。除此之外,WAR包中会包含很多Web资源,比如html、jsp、图片等。

  • /webapp(WebRoot) —— 根目录,至少包含两个子目录META-INFWEB-INF
  • /webapp/META-INF —— 包含一些打包元数据信息。
  • /webapp/WEB-INF —— 最安全的目录、保存配置文件、第三方jar包、各种类。
  • /webapp/web.xml —— web项目的配置文件(Web资源描述文件web.xml)。
  • /webapp/WEB-INF/classes —— 保存编译后的.class文件以及.xml或*.properties配置文件。
  • /webapp/WEB-INF/lib —— 保存所有Web项目的依赖的第三方jar包。
  • /webapp/WEB-INF/jsp —— 保存所有*.jsp文件,外部无法直接访问。
  • /webapp/css —— 保存所有*.css文件。
  • /webapp/img —— 保存所有图片。
  • /webapp/js —— 保存所有*.js文件。

一个典型的WAR文件如下目录结构:

└── webapp
    ├── META-INF
    ├── WEB-INF
    │   ├── classes
    │   │   ├── ***
    │   │   ├── Servlet.class
    │   │   └── config.properties
    │   ├── index.jsp
    │   ├── jsp
    │   ├── lib
    │   └── web.xml
    ├── css
    ├── img
    └── js

Maven目录结构初识

  • pom.xml所在的目录应为项目的根目录,假设该目录为${proj-name}
  • ${proj-name}/src/main/java —— 存放项目的.java文件。
  • ${proj-name}/src/main/resources —— 存放项目资源文件,如spring, hibernate配置文件。
  • ${proj-name}/src/test/jave —— 存放所有测试.java文件,如JUnit测试类。
  • ${proj-name}/src/test/resources —— 测试资源文件。
  • ${proj-name}/target —— 项目输出位置。

Idea自动生成Maven初始目录结构

├── pom.xml
└── src
    └── main
        └── webapp
            ├── WEB-INF
            │   └── web.xml
            └── index.jsp

基于Maven的Java Web(使用SSM框架)项目最终目录结构

├── pom.xml
├── src
│   ├── main
│   │   ├── java
│   │   │   └── cn
│   │   │       └── hbson
│   │   │           └── webssm
│   │   │               ├── controller
│   │   │               │   ├── converter
│   │   │               │   └── propertyeditor
│   │   │               ├── mapper
│   │   │               │   ├── XXXMapper.java
│   │   │               │   └── XXXMapper.xml
│   │   │               ├── po
│   │   │               ├── service
│   │   │               │   ├── XXXService.java
│   │   │               │   └── impl
│   │   │               │       └── XXXServiceImpl.java
│   │   │               └── utils
│   │   ├── resources
│   │   │   ├── jdbc.properties
│   │   │   ├── log4j.properties
│   │   │   ├── mybatis
│   │   │   │   └── sqlMapConfig.xml
│   │   │   └── spring
│   │   │       ├── applicationContext-dao.xml
│   │   │       ├── applicationContext-service.xml
│   │   │       ├── applicationContext-transation.xml
│   │   │       └── springmvc.xml
│   │   └── webapp
│   │       ├── META-INF
│   │       ├── WEB-INF
│   │       │   ├── jsp
│   │       │   └── web.xml
│   │       ├── img
│   │       ├── index.jsp
│   │       └── js
│   └── test
│       ├── java
│       └── resources
└── webssm.iml

完善目录结构(基于Maven的Java Web)

  • 右键 new Directory     在各个目录下分别创建Directory(test、java、resources、spring、mybatis、jsp)
  • 选中java右键 Make Directory as > Sources Root
  • 选中resources右键 Make Directory as > Resources Root
  • 选中test右键 Make Directory as > Test Sources Root

配置Tomcat

  • 点击 idea右上角的白色方框 > Edit Configuraion...
  • 添加 Tomcat Server > Local
  • 点击 Deployment > + > Artifact... > proj-name:war exploded (右边的Application Context是使用浏览器访问你的web应用(项目)的根路径)

测试项目部署

  访问 http://localhost:8080,出现Hello World!的页面。到此你完成了JavaWeb的项目结构并且部署成功,接下来完成Spring、SpringMVC、Mybatis的配置

项目配置文件

Maven配置文件,添加项目依赖的jar包 – pom.xml

  使用maven来引入项目所需要的jar包,通过maven自动下载管理jar包。

<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>
    <!-- spring版本号 -->
    <spring.version>4.2.5.RELEASE</spring.version>
    <!--mybatis版本号-->
    <mybatis.version>3.2.8</mybatis.version>
    <!--mysql驱动版本号-->
    <mysql-driver.version>5.1.29</mysql-driver.version>
    <!--log4j日志包版本号-->
    <slf4j.version>1.7.18</slf4j.version>
    <log4j.version>1.2.17</log4j.version>
  </properties>

  <dependencies>
    <!--添加jstl依赖-->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>7.0</version>
    </dependency>

    <!--添加junit4依赖-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <!-- 指定范围,在测试时才会加载 -->
      <scope>test</scope>
    </dependency>

     <!--添加spring核心依赖 -->
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
      </dependency>

      <!--添加spring和javaweb工程集成的jar包-->
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <!--添加spring事务-->
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-tx</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <!--添加spring JDBC-->
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>${spring.version}</version>
      </dependency>
      <!--添加spring AOP-->
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aop</artifactId>
          <version>${spring.version}</version>
      </dependency>

      <!-- 添加mybatis依赖 -->
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>${mybatis.version}</version>
      </dependency>
      <!-- 添加mybatis/spring整合包依赖 -->
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis-spring</artifactId>
          <version>1.2.2</version>
      </dependency>
      <!-- 添加mysql驱动依赖 -->
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>${mysql-driver.version}</version>
      </dependency>
      <!-- 添加数据库连接池 -->
      <dependency>
          <groupId>commons-dbcp</groupId>
          <artifactId>commons-dbcp</artifactId>
          <version>1.2.2</version>
      </dependency>

      <!-- 添加日志相关jar包 -->
      <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>${log4j.version}</version>
      </dependency>
      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
          <version>${slf4j.version}</version>
      </dependency>
      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
          <version>${slf4j.version}</version>
      </dependency>
      <!--添加aspectjweaver包 -->
      <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjweaver</artifactId>
          <version>1.8.5</version>
      </dependency>

  </dependencies>

工程配置信息 – web.xml

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

<display-name>Archetype Created Web Application</display-name>

  <!-- 配置spring容器监听器,加载spring配置 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext-*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:log4j.properties</param-value>
  </context-param>

  <!-- 编码过滤器 -->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!-- spring mvc  前端控制器 -->
  <servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/springmvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <!-- 可以配置/ ,此工程所有请求全部由springmvc解析,此种方式可以实现 RESTful方式,需要特殊处理对静态文件的解析不能由springmvc解析
			可以配置*.do或*.action,所有请求的url扩展名为.do或.action由springmvc解析,此种方法常用 不可以/*,如果配置/*,返回jsp也由springmvc解析,这是不对的。 -->
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

</web-app>

Jdbc配置文件 – jdbc.properties  

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_ssm?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
jdbc.username=root
jdbc.password=root

#定义初始连接数
jdbc.initialSize=0
#定义最大连接数
jdbc.maxActive=20
#定义最大空闲
jdbc.maxIdle=20
#定义最小空闲
jdbc.minIdle=1
#定义最长等待时间
jdbc.maxWait=60000  

Log4j配置文件 – log4j.properties

log4j.rootLogger=INFO,Console,File  
  
#控制台日志  
log4j.appender.Console=org.apache.log4j.ConsoleAppender  
log4j.appender.Console.Target=System.out  
log4j.appender.Console.layout=org.apache.log4j.PatternLayout  
log4j.appender.Console.layout.ConversionPattern=[%p][%t][%d{yyyy-MM-dd HH\:mm\:ss}][%C] - %m%n  
  
#普通文件日志  
log4j.appender.File=org.apache.log4j.RollingFileAppender  
log4j.appender.File.File=logs/ssm.log  
log4j.appender.File.MaxFileSize=10MB  
#输出日志,如果换成DEBUG表示输出DEBUG以上级别日志  
log4j.appender.File.Threshold=ALL  
log4j.appender.File.layout=org.apache.log4j.PatternLayout  
log4j.appender.File.layout.ConversionPattern=[%p][%t][%d{yyyy-MM-dd HH\:mm\:ss}][%C] - %m%n 

Mybatis的配置文件 – sqlMapConfig.xml  

<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 定义 别名 -->
    <typeAliases>
        <!-- 批量别名定义 指定包路径,自动扫描包下边的pojo,定义别名,别名默认为类名(首字母小写或大写) -->
        <package name="cn.hbson.webssm.po" />
    </typeAliases>
    <!--
    由于使用spring和mybatis整合的mapper扫描器,这里可以不用配置了
    <mappers>
        <package name="cn.itcast.ssm.mapper" />
    </mappers> -->
</configuration>

SpringMVC的配置文件 – springmvc.xml    

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

	<!-- 使用spring组件 自动扫描  @Controller -->
	<context:component-scan base-package="cn.hbson.webssm.controller" />

	<!-- 通过annotation-driven可以替代下边的处理器映射器和适配器 -->
<!-- 	<mvc:annotation-driven conversion-service="conversionService">
</mvc:annotation-driven>
	-->
	<!-- 注解处理器映射器 -->
	<bean
		class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
	</bean>
	<!-- 注解适配器 -->
	<bean
		class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
		<!-- 在webBindingInitializer中注入自定义属性编辑器、自定义转换器 -->
		<!--<property name="webBindingInitializer" ref="customBinder"></property>-->
	</bean>
	<!-- 配置视图解析器 需要jstl的jar包 -->
	<!-- ViewResolver  定义跳转的文件的前后缀 ,视图模式配置 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
	<!-- 自定义webBinder -->
	<!--<bean id="customBinder"-->
		<!--class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">-->
		<!--&lt;!&ndash; 使用converter进行参数转 &ndash;&gt;-->
		<!--<property name="conversionService" ref="conversionService" />-->
	<!--</bean>-->
	<!-- 注册属性编辑器 -->
	<!--<bean id="customPropertyEditor" class="cn.hbson.webssm.controller.propertyeditor.CustomPropertyEditor"></bean>-->
	<!-- 转换器 -->
    <!--<bean id="conversionService"-->
		<!--class="org.springframework.format.support.FormattingConversionServiceFactoryBean">-->
		<!--<property name="converters">-->
			<!--<list>-->
				<!--<bean class="cn.hbson.webssm.controller.converter.CustomDateConverter"/>-->
				<!--<bean class="cn.hbson.webssm.controller.converter.StringTrimConverter"/>-->
			<!--</list>-->
		<!--</property>-->
	<!--</bean>-->
</beans>

Spring和Mybatis整合所需的配置文件(Dao层的配置文件) – applicationContext-dao.xml

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

	<!-- 加载jbdc.properties配置文件 -->
	<context:property-placeholder location="classpath:jdbc.properties" />
	<!-- 配置数据库连接池 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="initialSize" value="${jdbc.initialSize}"/>
		<property name="maxActive" value="${jdbc.maxActive}" />
		<property name="maxIdle" value="${jdbc.maxIdle}" />
		<property name="minIdle" value="${jdbc.minIdle}" />
		<property name="maxWait" value="${jdbc.maxWait}"/>
	</bean>


	<!-- SqlsessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 数据源 -->
		<property name="dataSource" ref="dataSource"/>
		<!-- mybatis配置文件 -->
		<property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml"/>
	</bean>

	<!-- 
	MapperScannerConfigurer:mapper的扫描器,将包下边的mapper接口自动创建代理对象,
	自动创建到spring容器中,bean的id是mapper的类名(首字母小写)
	 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 配置扫描包的路径
		如果要扫描多个包,中间使用半角逗号分隔
		要求mapper.xml和mapper.java同名且在同一个目录
		 -->
		<property name="basePackage" value="cn.hbson.webssm.mapper"/>
		<!-- 使用sqlSessionFactoryBeanName -->
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
	</bean>
</beans> 

Service层Spring配置文件 – applicationContext-service.xml

配置service层的bean

<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"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!-- 这里添加service层需要配置的bean-->
</beans>

Spring事务配置文件 – applicationContext-transation.xml

<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"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
	 <!-- 使用声明式事务配置,可以有效规范代码 -->
	 <!-- 事务管理器 -->
	 <bean id="transactionManager" 
	 		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	 	<property name="dataSource" ref="dataSource"/>
	 </bean>
	 
	 <!-- 通知 -->
	 <tx:advice id="txAdvice" transaction-manager="transactionManager">
	 	<tx:attributes>
	 		<tx:method name="save*" propagation="REQUIRED"/>
	 		<tx:method name="insert*" propagation="REQUIRED"/>
	 		<tx:method name="update*" propagation="REQUIRED"/>
	 		<tx:method name="delete*" propagation="REQUIRED"/>
	 		<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
	 		<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
	 		<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
	 	</tx:attributes>
	 </tx:advice>
	 
	 <!-- aop -->
	 <aop:config>
	 	<aop:advisor advice-ref="txAdvice"
	 				 pointcut="execution(* cn.hbson.webssm.service.impl.*.*(..))"/>
	 </aop:config>
	
</beans>