这一步是加入spring的事务功能。
事务,就是要他的ACDI特性。
这里是遇到运行时异常回滚,受查异常提交。
step9:
所以我们写的异常,一定是运行时异常。
配置spring-tx.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: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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- AOP -->
<!-- 注册事务管理器 -->
<bean id="MyTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="MyDataSource"></property>
</bean>
<!-- 注册事务注解驱动 -->
<tx:annotation-driven transaction-manager="MyTransactionManager"/>
</beans>
这里可以看到,就两件事,而且,id应该是不能变的吧,我记得是这里,ID不能自定义。
业务类加上注解
@Transactional(isolation=Isolation.DEFAULT, propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
public boolean Register(Person p) throws Exception {
// TODO 自动生成的方法存根
// 测试事务
pdao.insertPerson(p);
// 抛出异常,这里应该不会执行的
if(1==1)
throw new Abrupt("意外中断");
return false;
}
这里可以看到,我抛出了异常,这个异常类非常简单,就是继承了Exception。
异常类
Abrupt.java
package com.ssmlogin.exception;
public class Abrupt extends Exception{
public Abrupt() {
super();
// TODO 自动生成的构造函数存根
}
public Abrupt(String message) {
super(message);
// TODO 自动生成的构造函数存根
}
}
在controller中写入注册方法:
@RequestMapping("/register")
public ModelAndView register(Person p, HttpSession session) throws Exception
{
ModelAndView mv = new ModelAndView();
if(ls.Register(p))
{
mv.setViewName("/regsuc.jsp");
}
else
{
mv.addObject("message", "注册失败");
mv.setViewName("/login.jsp");
}
return mv;
}
这里代码就能跑起来了,在点击注册之后,要插入的数据应该是失败的,因为抛出异常了。
当然到这里,你所看到的页面应该是服务器的500页面,所以这里还需要添加异常捕获,接下来的文章会说。
如果我的内容在哪里有问题,欢迎私信指正。