创建maven项目
1.导入相关依赖
<dependencies>
<!--单元测试的依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--AOP相关依赖-->
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.9</version>
</dependency>
<!--数据源-->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!--使用连接池-->
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.6</version>
</dependency>
<!--打印日志相关的依赖-->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--mybatis框架的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.2</version>
</dependency>
<!--mybatis与spring整合的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.0</version>
</dependency>
<!--连接数据库的依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<!--spring相关的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>3.2.13.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.2.13.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.13.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.13.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>3.2.13.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.2.13.RELEASE</version>
</dependency>
<!--使用spring声明式事务的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>3.2.13.RELEASE</version>
</dependency>
<!--springMVC相关依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.2.13.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.13.RELEASE</version>
</dependency>
<!--数据转json格式的依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.13</version>
</dependency>
<!--Tomcat相关依赖-->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>8.5.32</version>
</dependency>
</dependencies>
2.配置web.xml文件(web层的配置文件)
配置前端控制器DispatcherServlet
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 初始applicationContext.xml:applicationContext.xml配置文件也可以使用<init-param>标签在servlet标签中进行配置 -->
<init-param>
<!--配置spring文件-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 配置请求地址拦截url -->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
配置监听器
该监听器作用是在启动web容器的时候,读取contextConfigLocation定义的spring配置文件,完成spring容器初始化,bean实例化等工作
<!--启动服务器(tomcat)时,就实例化IOC容器并完成Bean的创建-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-mybatis.xml</param-value>
</context-param>
3.在resources目录下创建相关配置文件
01 创建database.properties文件(连接数据库的配置文件)
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost/数据库名?useUnicode=true&characterEncoding=utf-8
user=root
password=1234
minIdle=45
maxIdle=50
initialSize=5
maxActive=100
maxWait=100
removeAbandonedTimeout=180
removeAbandoned=true
02.创建log4j.properties打印日志的配置文件,用于查看日志信息,sql相关语句
log4j.rootLogger=debug,CONSOLE
log4j.logger.mapper层的目录=debug
log4j.logger.org.apache.ibatis=debug
log4j.logger.org.mybatis.spring=debug
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug
log4j.logger.java.sql.ResultSet=debug
######################################################################################
# Console Appender \u65e5\u5fd7\u5728\u63a7\u5236\u8f93\u51fa\u914d\u7f6e
######################################################################################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=debug
log4j.appender.CONSOLE.DatePattern=yyyy-MM-dd
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= - (%r ms) - %d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
03. 创建mybatis-config.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>
<typeAliases>
<!--这里给实体类取别名,方便在mapper配置文件中使用-->
<package name="cn.smbms.pojo"/>
</typeAliases>
</configuration>
04.创建applicationContext-mybatis.xml文件(spring配置文件)
001.引入命名空间(带声明式事务)
002.开启组件扫描和AOP的自动代理(扫持久层与业务层的Bean)
<context:component-scan base-package="需要扫的包"/>
<aop:aspectj-autoproxy/>
003.读取数据库的配置文件
<context:property-placeholder location="classpath:database.properties"/>
004.配置数据源(使用dbcp连接池)
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" scope="singleton">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${user}"/>
<property name="password" value="${password}"/>
<!-- 数据库连接池在初始化连接时,第一次就要创建的连接个数 -->
<property name="initialSize" value="${initialSize}"/>
<!-- 定义连接池中同时连接的最大连接数,默认为8。 -->
<property name="maxActive" value="${maxActive}"/>
<!-- 定义连接池中同时连接的最大空闲连接数,默认是8 -->
<property name="maxIdle" value="${maxIdle}"/>
<!-- 定义连接池中最小的连接数,默认是0 低于该数值的连接池将会创建新的连接 -->
<property name="minIdle" value="${minIdle}"/>
<!-- 定义最大等待时间,单位为ms -->
<property name="maxWait" value="${maxWait}"/>
<!-- 当开启了无用连接回收的机制之后,配置该配置项可以控制连接池在超出配置的时间后回收没有用的连接,默认为30秒 -->
<property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}"/>
<!-- 定义该配置项的作用是告诉连接池是否开启无用连接回收的机制,默认是false -->
<property name="removeAbandoned" value="${removeAbandoned}"/>
<!-- sql 心跳 -->
<!-- 定义开启Evict的定时校验,单位为毫秒 -->
<!--指明连接是否被空闲连接回收器(如果有)进行检验.如果检测失败,则连接将被从池中去除-->
<!--注意: 设置为true后如果要生效,validationQuery参数必须设置为非空字符串-->
<property name="testWhileIdle" value="true"/>
<!--指明是否在从池中取出连接前进行检验,如果检验失败, 则从池中去除连接并尝试取出另一个-->
<!--注意: 设置为true后如果要生效,validationQuery参数必须设置为非空字符串-->
<property name="testOnBorrow" value="false"/>
<!--指明是否在归还到池中前进行检验-->
<!--注意: 设置为true后如果要生效validationQuery参数必须设置为非空字符串-->
<property name="testOnReturn" value="false"/>
<!--SQL查询,用来验证从连接池取出的连接,在将连接返回给调用者之前-->
<!--如果指定,则查询必须是一个SQL SELECT并且必须返回至少一行记录-->
<property name="validationQuery" value="select 1"/>
<!--设置的Evict线程的时间,单位:毫秒,即每隔多少时间去检测一次空闲连接是否超时
(大于timeBetweenEvictionRunsMillis的值),默认值为-1,即不开启-->
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<!--设定在进行后台对象清理时,每次检查几个链接。默认值是3-->
<property name="numTestsPerEvictionRun" value="${maxActive}"/>
</bean>
005.配置mybitas SqlSessionFactoryBean 容器中其他的bean就可以使用SqlSession
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 引用数据源组件 -->
<property name="dataSource" ref="dataSource" />
<!-- 引用MyBatis配置文件中的配置 -->
<property name="configLocation" value="classpath:mybatis-config.xml" />
<!--指定mapper映射文件位置-->
<property name="mapperLocations">
<list>
<value>classpath:mapper/*.xml</value>
</list>
</property>
</bean>
006.配置DAO(mapper)层
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--MapperScannerConfigurer扫描这个包以及子包中所有的接口,
如果这些接口在SQL映射文件中定义过,就会自动的生成接口的实现类-->
<property name="basePackage" value="cn.kgc.mapper" />
</bean>
007.配置声明式事务———第五节开始
05.创建springmvc-servlet.xml文件(springmvc的配置文件)
002.开启组件扫描(扫Controller层)
<context:component-scan base-package="cn.smbms.controller"/>
003. 配置消息转换器,解决格式乱码的问题
<mvc:annotation-driven>
<mvc:message-converters>
<bean id="fastJsonHttpMessageConverter"
class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<!--加入支持的媒体类型 返回contentType类型-->
<property name="supportedMediaTypes">
<list>
<!--这里的顺序不能反,一定要先标注text/html的格式,不然ie下会出现下载提示-->
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
4.创建各层的包
5.自定义Filter拦截请求,添加跨域请求支持
创建过滤器类CorsConfig
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CorsConfig implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.addHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
System.out.println("request.getMethod():" + request.getMethod());
if ("OPTIONS".equals(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
return;
}
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
6.在web.xml配置过滤器
<filter>
<filter-name>corsFilter</filter-name>
<!--过滤器类的全包名-->
<filter-class>路径</filter-class>
</filter>
<filter-mapping>
<filter-name>corsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>