1、eclipse通过Data Source Explorer连接mysql数据库
配置驱动时需关联到本地的mysql连接的jar包,连接字符串加上编码设置
2、项目中导入mysql连接的jar包,设置Build Path
复制mysql-connector-java-5.1.46.jar到WebContent/WEB-INF/lib
3、创建JdbcUtils工具类,获取数据库连接
(1)在静态块,通过类全名加载mysql连接驱动,异常向上抛出
Class.forname("com.mysql.jdbc.Driver");
throw new RuntimeException(e);
(2)定义一个获取连接的方法,
public static Connection getConnection()
通过DriverManager.getConnection(url,username,password)方法配置数据库返回连接
4、创建models类
类,对应数据库表
类的属性,对应数据库字段
一个对象,对应数据库一条记录
所有属性生成get和set方法,以及toString方法
5、创建Dao实现类
创建数据库操作方法,如save、delete、update方法
步骤:
(1)定义数据库连接和执行脚本对象,Connection以及PrepareStatement
(2)创建sql脚本
(3)sql脚本传入Preparestatement并设置参数
(4)执行脚本
(5)释放资源,关闭执行对象,关闭数据库连接
6、创建BaseDao父类,抽取Dao实现类中的增删改共性代码,并在Dao类中继承
(1)父类的方法传入两个参数,sql脚本和数据库参数,数据库参数以Object数组对象传入
(2)通过for循环把Object数组的值依次配置给sql参数
(3)在子类中通过super调用父类方法,将sql脚本和数据库参数数组传入
7、引入Junit单元测试
(1)在项目Build Path-Libraries-Add Libary-Junit4
(2)创建单元测试包和测试类,注意~!类和方法需要声明为public
(3)创建一个DaoImpl实现类的静态对象,用于测试调用
(4)@BeforeClass,@AfterClass注解为测试前后调用的方法,用于初始化和释放资源
(5)测试方法用@Test注解
8、查询数据
(1)除了增删改方法需要的数据库连接和执行脚本对象,需要在Dao实现类定义一个ResultSet对象用于存放查询结果,如查询多行数据,需定义一个List<>对象返回结果。如查询单行数据,需定义一个models对象
(2)用ResultSet对象的next()方法判断查询的数据行数,通过ResultSet的getString等方法将每一个字段值遍历放入ArrayList或models对象
9、在父类抽取查询方法,适用所有model对象查询
(1)父类定义为抽象类,T类型
(2)定义一个抽象方法,获取查询结果
(3)定义T类型的查询方法,将抽象方法中的类型返回
(4)子类继承父类时,需指明T的具体类型
(5)需重写@Override父类的抽象方法,将查询结果指定为所需数据库类型
10、导入spring框架
(1)添加spring相关jar包,以及c3p0相关jar包
(2)创建spring配置文件,bean对应java类,property对应属性,有对应的set方法
配置文件:
<!-- 给连接池配置连接数据库四大参数 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/review?useUnicode=true&characterEncoding=utf8" />
<property name="user" value="root" />
<property name="password" value="123456" />
</bean>
11、采用spring对Dao的增、删、改进行重构
(1)xml文件中需添加jdbctemplate的bean,实现增删查改操作,定义dataSource属性,依赖dataSource
(2)xml文件中添加Dao类的bean,定义jdbctemplate属性,依赖jdbctemplate
(3)Dao实现类中定义JdbcTemplate对象,并定义set方法
(4)将Dao的数据库操作替换为jdbcTemplate方法
(5)在测试类中,需定义配置文件加载对象,在测试前初始化方法中加载配置文件,
private static ApplicationContext context = null;
context = new ClassPathXmlApplicationContext("spring-bean.xml");
noticedao = context.getBean("NoticeDaoImpl", NoticeDaoImpl.class);
(6)可删除JdbcUtils、BaseDaoImpl类
12、通过spring提供RowMap完成查询的操作
(1)在Dao实现类中通过jdbcTemplate方法执行查询语句
(2)jdbcTemplate.queryForObject(sql脚本,RowMapper对象,传入参数),查询返回单个对象
RowMap:new BeanPropertyRowMapper(Model.class)
jdbcTemplate.query(sql脚本,RowMapper对象,传入参数),查询返回列表
RowMap:new BeanPropertyRowMapper(Model.class),
传入多个参数:new Object[]{?, ? ,?}
注意~!,如果类的属性与数据库字段名不一致,查询结果为null。
13、添加service层
(1)创建service包,创建service实现类
(2)xml文件中添加service实现类的bean,依赖Dao
(3)在service实现类中定义Dao对象,并定义set方法以及各操作方法
14、配置声明式事务管理
(1)在xml文件中添加aop,tx标签
(2)定义事务管理器的bean,依赖datasource
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
(3)定义事务
<tx:advice id="advice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="*" propagation="NEVER"/>
</tx:attributes>
</tx:advice>
(4)定义事务切入的层
<aop:config>
<aop:pointcut expression="execution(* com.huizhou.service.*.*(..))" id="pointcut"/>
<aop:advisor advice-ref="advice" pointcut-ref="pointcut"/>
</aop:config>
其中
* 代表此方法有无返回值都可
com.huizhou.service: 代表要切入的包,一般都是存储service的包
com.huizhou.service.*:代表当前包的所有类
com.huizhou.service..: 代表当前包的所有类的所有方法
(..): 有无参数都可以
15、配置日志和异常处理
(1)创建AopClass的工具类
定义日志和异常的处理方法,
日志处理方法的传参为JoinPoint类型,其中:
jp.getTarget(),被切的目标对象
jp.getSignature(),被切的方法声明
Arrays.toString(jp.getArgs()),被切的方法参数信息
异常的传参类型为Exception类型
(2)xml文件中定义Aop的bean,类型为AopClass工具类
(3)xml文件中配置日志和异常管理
<aop:config>
<aop:aspect ref="aop">
<aop:pointcut expression="execution(* com.huizhou.service.*.*(..))" id="aop_pointcut"/>
<aop:after-returning method="logs" pointcut-ref="aop_pointcut"/>
<aop:after-throwing method="ex" throwing="e" pointcut-ref="aop_pointcut"/>
</aop:aspect>
</aop:config>
其中,method中的方法,与AopClass中的方法名一致,异常管理中throwing中的参数与AopClass中的传参名一致
16、控制aop切入的顺序
在事务管理中的aop:advisor,或在日志和异常处理中的aop:aspect加入order属性
17、添加项目到Tomcat
(1)添加Server窗口,选择Apache-Tomcat-选择Tomcat路径,先不添加项目
(2)进入tomcat配置,选择项目打包路径
(3)项目Bulid Path,Add Libary-Server Runtime-tomcat
(4)在WebContent下创建jsp页面,编码指定UTF-8,Tomcat启动后通过http://localhost:8080/工程名/页面.jsp访问
18、spring与aop配置文件分离
创建spring-public.xml,包含数据库连接、事务管理配置
创建spring-aop.xml,包含日志和异常处理配置
19、spring-mvc框架搭建
(1)创建Controller类,此类需要添加@Controller注解,
定义serviceImpl对象,调用service对象的方法访问数据库,需通过@Resource注解依赖service,name值与spring配置文件中的service一致,不能为static
Controller类和方法,都需要添加@RequesMapping注解来控制访问地址。
(2)创建mvc-public.xml,context:component-scan开启包扫描,将controller包扫描
<context:component-scan base-package="com.huizhou.controller"></context:component-scan>
(3)在WEB-INF目录下创建web.xml,为项目启动入口,加载spring和mvc的配置文件
<display-name>review_web</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-*.xml,classpath:mvc-*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.mvc</url-pattern>
</servlet-mapping>
其中,contextConfigLocation参数的内容为加载配置文件的路径;
load-on-startup参数为项目启动时即刻加载配置文件;
url-pattern参数,过滤css、js等url,仅包含mvc的url通过框架访问。
(4)前端页面中,通过<%=request.getContextPath()%>获取工程路径,加上Controller中的Mapping的值访问,注意是mvc的url地址,前端name的值需要与后台传入参数名称一致。
20、创建查询页面
(1)导入jstl和standard包
(2)创建BaseController类,定义全局变量,需添加@Resource注解,不用添加名称
@Resource
protected HttpServletRequest request;
@Resource
protected HttpSession session;
@Resource
protected ServletContext application;
(3)Controller需继承BaseController,获取全局变量
所有方法都定义为String类型,并返回值为跳转页面字符串,其中”redirect:/”为重定向,”forward:/”为转发,存在数据共享
全局变量通过setAttribute设值,并在前端页面获取
(4)前端获取数据,需导入jstl标签
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
在页面中,通过标签循环获取数据,
<c:forEach items="${requestScope.proList}" var="product">
<tr>
<td>${product.id}</td>
<td>${product.name}</td>
<td>${product.price}</td>
<td>${product.remark}</td>
<td>${product.date}</td>
<td>更新|删除</td>
</tr>
</c:forEach>
其中,requestScope可以获取全局变量,同理sessionScope,applicationScope
20、使用bootstrap框架
(1)在WebContent目录下新建css和js文件夹,分别放入bootstrap.min.css,bootstrap.min.js,jquery-3.2.1.min.js
(2)在前端页面中引入框架
<link rel="stylesheet" href="/review_web/css/bootstrap.min.css">
<script type="text/javascript" src="/review_web/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/review_web/js/jquery-3.2.1.min.js"></script>
21、使用mybatis框架
(1)导入mybatis、mybatis-spring的jar包
(2)在src目录下创建mybatis.cfg.xml配置文件,配置包括model扫描和mapper扫描
<?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>
<package name="com.huizhou.models"/>
</typeAliases>
<mappers>
<package name="com.huizhou.dao"/>
</mappers>
</configuration>
(3)在Dao目录上创建Dao接口,与Dao实现xml对应,定义的方法与xml中的标签id一致,
如果方法传入多个类型参数,则通过@Param绑定参数,例如:
public List<Product> queryByName(@Param("name") String name, @Param("start") int start, @Param("end") int end);
(4)在Dao目录下创建实现类的xml文件,定义mapper,包括了数据库查询语句的定义
定义mapper标签,命名空间与接口类名称一致。
定义数据库查询语句,需定义id和传参属性,如果返回结果,需定义返回类型,传入参数通过#{}引用,例如:
<insert id="save" parameterType="product">
insert into product(name, price, remark) values (#{name},#{price},#{remark})
</insert>
如果语句不确定,通过和标签组合,例如:
<update id="update" parameterType="product">
update product
<set>
<if test="name!=null">
name = #{name},
</if>
<if test="price!=null">
price = #{price},
</if>
<if test="remark!=null">
remark = #{remark},
</if>
</set>
where id = #{id}
</update>
如果传入多个类型参数,则在xml中不用定义参数类型,在接口类中通过@Param绑定参数,例如:
<select id="queryByName" resultType="product">
select * from product where name like #{name} limit #{start}, #{end}
</select>
(5)在Service类中替换原Dao实现类,改成Dao接口,删除Dao实现类
(6)替换spring-public.xml中jdbcTemplate和dao实现的配置,替换成sqlSessionFactory和mapper,分别配置为mybatis.cfg.xml和Dao实现xml文件,或通过包扫描
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:mybatis.cfg.xml"></property>
</bean>
<bean id="productDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.huizhou.dao.ProductDao"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
或包扫描
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.huizhou.dao"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
22、通过resultMap解决数据库列名与model属性不一致问题
在dao实现xml文件中,定义resultMap标签
<resultMap type="product" id="baseMap">
<id property="id" column="pro_id"></id>
<result property="name" column="pro_name"/>
<result property="price" column="pro_price"/>
<result property="remark" column="pro_remark"/>
<result property="date" column="pro_date"/>
</resultMap>
23、多表连接
(1)多对一
在model类里加入连接的对象本身作为属性,并设置get和set方法;
在dao实现的xml文件里,定义一个resultMap,继承baseMap,通过标签,属性为需要连接的列名,值为需要连接的对象的baseMap,并添加到对应的数据库语句中的resultMap
<resultMap type="product" id="joinCategory" extends="baseMap">
<association property="category" resultMap="com.huizhou.dao.CategoryDao.baseMap"></association>
</resultMap>
<select id="queryByName" resultMap="joinCategory">
select * from product p join category c on p.cat_id = c.cat_id where p.pro_name like #{name} limit #{start}, #{end}
</select>
(2)一对多
在model类里加入连接的对象列表作为属性,并设置get和set方法;
在dao实现的xml文件里,定义一个resultMap,继承baseMap,通过标签,属性为需要连接的列名,值为需要连接的对象的baseMap,并添加到对应的数据库语句中的resultMap
<resultMap type="category" id="joinProduct" extends="baseMap">
<collection property="proList" resultMap="com.huizhou.dao.ProductDao.baseMap"></collection>
</resultMap>
<select id="queryByName" parameterType="string" resultMap="joinProduct">
select * from category c join product p on c.cat_id=p.cat_id where c.cat_name like #{name}
</select>
(3)在Dao实现xml文件中,如果语句存在多个model的数据,需通过类的方法获取数据,例如:
<insert id="save" parameterType="product">
insert into product(pro_name, pro_price, pro_remark, cat_id) values (#{name},#{price},#{remark},#{category.id})
</insert>
24、解决中文乱码问题
(1)在spring-public.xml配置文件中的数据库连接部分,url连接需要配置为:
jdbc:mysql://localhost:3306/review?useUnicode=true&characterEncoding=utf8
(2)在web.xml配置文件中,加入过滤器的配置
<filter>
<filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
25、配置web.xml中的加载顺序,通过监听器加载spring配置文件
web组件的有先级别:Servlet < Filter < ServletContextListener
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-public.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
26、添加缓存
(1)添加ehcache、mybatis-ehcache的jar包
(2)在Dao实现xml文件里,配置缓存功能
<cache type="org.mybatis.caches.ehcache.LoggingEhcache"></cache>
(3)在src目录下创建ehcache.xml文件,
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="2"
eternal="true"
timeToIdleSeconds="3"
timeToLiveSeconds="5"
overflowToDisk="false"
memoryStoreEvictionPolicy="LFU"/>
</ehcache>
27、添加日志包
(1)添加log4j的jar包
(2)在src目录下创建log4j.properties
log4j.rootLogger=debug,stdout,logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=jbit.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
28、日期时间格式化
1、model类,在日期属性上添加注解@DateTimeFormat(pattern=”yyyy-MM-dd HH:mm:ss”)
2、
<mvc:annotation-driven></mvc:annotation-driven>