1、异常处理机制
异常类有两个主要的子类:IOException 类和 RuntimeException 类。
1、异常处理的思路
系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后 者主要通过规范代码开发、测试等手段减少运行时异常的发生。
系统的Dao、Service、Controller出现都通过throws Exception向上抛出,最后由SpringMVC前端控制器交 由异常处理器进行异常处理,如下图:
2、异常处理两种方式
1、使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver
SpringMVC已经定义好了该类型转换器,在使用时可以根据项目情况进行相应异常与视图的映射配置
<!--配置异常处理器--><beanclass="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"><!–<propertyname="defaultErrorView"value="error"/>–> <propertyname="exceptionMappings"><map><entrykey="java.lang.ClassCastException"value="error1"/><entrykey="com.xmp.exception.MyException"value="error2"/></map></property></bean>
2、实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器
① 创建异常处理器类实现HandlerExceptionResolver
publicclassMyExceptionResolverimplementsHandlerExceptionResolver { publicModelAndViewresolveException(HttpServletRequestrequest, HttpServletResponseresponse, Objecthandler, Exceptionex) { //处理异常的代码实现//创建ModelAndView对象ModelAndViewmodelAndView=newModelAndView(); modelAndView.setViewName("exceptionPage"); returnmodelAndView; } }
② 配置异常处理器
<bean id="exceptionResolver" class="com.xmp.exception.MyExceptionResolver"/>
③ 编写异常页面
<%pagecontentType="text/html;charset=UTF-8"language="java"%><html><head><title>Title</title></head><body>这是一个最终异常的显示页面</body></html>
④ 测试异常跳转
"/quick22") (publicvoidquickMethod22() throwsIOException, ParseException { SimpleDateFormatsimpleDateFormat=newSimpleDateFormat("yyyy-MM-dd"); simpleDateFormat.parse("abcde"); }
2、Spring练习Demo
1、Spring练习环境搭建
① 创建工程(Project&Module)
② 导入静态页面
放到文章最后,主要学习Spring,没有注重前端页面的编写。
③ 导入需要坐标
<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="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/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>xmp</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.32</version></dependency><dependency><groupId>c3p0</groupId><artifactId>c3p0</artifactId><version>0.9.1.2</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.10</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.0.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.0.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>5.0.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.0.5.RELEASE</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.0.1</version><scope>provided</scope></dependency><dependency><groupId>javax.servlet.jsp</groupId><artifactId>javax.servlet.jsp-api</artifactId><version>2.2.1</version><scope>provided</scope></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.9.0</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.0</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.9.0</version></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.3</version></dependency><dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>1.2</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.7</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.0.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>5.0.5.RELEASE</version></dependency><dependency><groupId>jstl</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency></dependencies></project>
④ 创建包结构(controller、service、dao、domain、utils等)
⑤ 导入数据库脚本
⑥ 创建POJO类
packagecom.xmp.pojo; importjava.util.List; publicclassUser { privateLongid; privateStringusername; privateStringemail; privateStringpassword; privateStringphoneNum; //当前用户具备哪些角色privateList<Role>roles; publicList<Role>getRoles() { returnroles; } publicvoidsetRoles(List<Role>roles) { this.roles=roles; } publicLonggetId() { returnid; } publicvoidsetId(Longid) { this.id=id; } publicStringgetUsername() { returnusername; } publicvoidsetUsername(Stringusername) { this.username=username; } publicStringgetEmail() { returnemail; } publicvoidsetEmail(Stringemail) { this.email=email; } publicStringgetPassword() { returnpassword; } publicvoidsetPassword(Stringpassword) { this.password=password; } publicStringgetPhoneNum() { returnphoneNum; } publicvoidsetPhoneNum(StringphoneNum) { this.phoneNum=phoneNum; } publicStringtoString() { return"User{"+"id="+id+", username='"+username+'\''+", email='"+email+'\''+", passwords='"+passwords+'\''+", phoneNum='"+phoneNum+'\''+'}'; } }
packagecom.xmp.pojo; publicclassRole { privateLongid; privateStringroleName; privateStringroleDesc; publicLonggetId() { returnid; } publicvoidsetId(Longid) { this.id=id; } publicStringgetRoleName() { returnroleName; } publicvoidsetRoleName(StringroleName) { this.roleName=roleName; } publicStringgetRoleDesc() { returnroleDesc; } publicvoidsetRoleDesc(StringroleDesc) { this.roleDesc=roleDesc; } publicStringtoString() { return"Role{"+"id="+id+", roleName='"+roleName+'\''+", roleDesc='"+roleDesc+'\''+'}'; } }
⑦ 创建配置文件(applicationContext.xml、spring-mvc.xml、jdbc.properties、log4j.properties)
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/testjdbc.username=rootjdbc.password=your_password
log4j.properties
###directlogmessagestostdout###log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p%c{1}:%L-%m%n###directmessagestofilemyLog.log###log4j.appender.file=org.apache.log4j.FileAppenderlog4j.appender.file.File=F:/myLog.loglog4j.appender.file.layout=org.apache.log4j.PatternLayoutlog4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p%c{1}:%L-%m%n###setloglevels-formoreverboseloggingchange'info'to'debug'###log4j.rootLogger=info, stdout
spring-mvc.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd
">
<!--1、mvc注解驱动-->
<mvc:annotation-driven/>
<!--2、配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--3、静态资源权限开放-->
<mvc:default-servlet-handler/>
<!--4、组件扫描 扫描Controller-->
<context:component-scan base-package="com.xmp.controller"/>
</beans>
<?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"
xsi:schemaLocation="
http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd
">
<!--1、加载jdbc.properties-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--2、配置数据源对象-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--3、配置JdbcTemplate对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置RoleService-->
<bean id="roleService" class="com.xmp.service.impl.RoleServiceImpl">
<property name="roleDao" ref="roleDao"/>
</bean>
<!--配置RoleDao-->
<bean id="roleDao" class="com.xmp.dao.impl.RoleDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
<!--配置UserService-->
<bean id="userService" class="com.xmp.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"/>
<property name="roleDao" ref="roleDao"/>
</bean>
<!--配置UserDao-->
<bean id="userDao" class="com.xmp.dao.impl.UserDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
</beans>
2、用户和角色的关系
3、角色列表的展示和添加操作
- 角色列表的展示步骤分析
① 点击角色管理菜单发送请求到服务器端(修改角色管理菜单的url地址)
② 创建RoleController和showList()方法
③ 创建RoleService和showList()方法
④ 创建RoleDao和findAll()方法
⑤ 使用JdbcTemplate完成查询操作
⑥ 将查询数据存储到Model中
⑦ 转发到role-list.jsp页面进行展示
- 角色添加的步骤分析
① 点击列表页面新建按钮跳转到角色添加页面
② 输入角色信息,点击保存按钮,表单数据提交服务器
③ 编写RoleController的save()方法
④ 编写RoleService的save()方法
⑤ 编写RoleDao的save()方法
⑥ 使用JdbcTemplate保存Role数据到sys_role
⑦ 跳转回角色列表页面
4、用户列表的展示和添加操作
- 用户列表的展示步骤分析
① 点击用户管理菜单发送请求到服务器端(修改用户管理菜单的url地址)
② 创建RoleController和showList()方法
③ 创建RoleService和showList()方法
④ 创建RoleDao和findAll()方法
⑤ 使用JdbcTemplate完成查询操作
⑥ 将查询数据存储到Model中
⑦ 转发到user-list.jsp页面进行展示
- 用户列表的添加步骤分析
① 点击列表页面新建按钮跳转到角色添加页面
② 输入角色信息,点击保存按钮,表单数据提交服务器
③ 编写RoleController的save()方法
④ 编写RoleService的save()方法
⑤ 编写RoleDao的save()方法
⑥ 使用JdbcTemplate保存Role数据到sys_role
⑦ 跳转回角色列表页面
5、删除用户操作
① 点击用户列表的删除按钮,发送请求到服务器端
② 编写UserController的deleteById()方法
③ 编写UserService的deleteById()方法
④ 编写UserDao的deleteById()方法
⑤ 编写UserDao的deleteRelByUid()方法
⑥ 跳回当前用户列表页面