编译期异常:Exception的直接子类 需要通过捕获/抛出异常来进行处理,不处理程序无法运行
运行时异常:RuntimeException的直接子类 可以不处理,程序可以正常运行 可以通过规范代码的编写,加强测试,严谨代码逻辑来避免异常的发生
系统开发使用mvc架构 dao service controller 在每一层都有可能发生异常,springmvc中,我们可以不自己处理,然后将异常层层往上抛出,到达controller在继续往上抛 抛给dispatcherServlet ,dispatcherServlet 在接收到异常信息之后,他可以交由异常处理器进行统一处理,
① 使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver
② 实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView" value="error"/>
<property name="exceptionMappings">
<map>
<entry key="java.lang. ClassCastException" value="cast">entry>
<entry key="java.lang.NullPointerException" value="null">entry>
map>
property>
bean>
public class MyEceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("excep");
return modelAndView;
}
}
自定义异常处理器需要实现HandlerExceptionResolver接口
配置自定义异常处理器
<bean id="myExceptionResolver" class="cn.lanqiao.exception.MyEceptionResolver">
对于自定义异常处理器和SimpleMappingExceptionResolver两个只需配置一个即可
异常处理试图
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
这是自定义异常的处理页面
public class MyException extends Exception{
private String message;
public MyException(String message){
this.message =message;
}
public String getMessage(){
return message;
}
}
@ControllerAdvice
public class GlobleExceptionHandlerResolver {
@ExceptionHandler(Exception.class)
public ModelAndView handle(Exception ex){
ex.printStackTrace();
//检测异常类型
MyException me=null;
if(ex instanceof MyException){
me = (MyException) ex;
}else{
me = new MyException("系统异常,请与管理员联系");
}
ModelAndView mv = new ModelAndView();
mv.addObject("message",me.getMessage());
mv.setViewName("glob");
return mv;
}
}
整合步骤:
整合思路:
整合方式: 整合的方式是多种多样:选择xml+注解方式
1 搭建环境
2 先把Spring的环境搭建好
3 搭建springmvc
4 将Sping和SpingMVC整合
5 搭建mybatis的环境
6使用Spring整合mybatis
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13version>
<scope>testscope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.21version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.2.2version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.2.12.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.2.12.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>5.2.12.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>5.2.12.RELEASEversion>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.9.6version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.5version>
dependency>
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelperartifactId>
<version>5.2.0version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.5version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jsp-apiartifactId>
<version>2.0version>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
/*
Navicat Premium Data Transfer
Source Server : mysql
Source Server Type : MySQL
Source Server Version : 50536
Source Host : localhost:3306
Source Schema : lanqiao
Target Server Type : MySQL
Target Server Version : 50536
File Encoding : 65001
Date: 29/04/2021 11:41:16
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`sid` int(11) NOT NULL COMMENT 'id',
`sname` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '姓名',
`age` int(11) NULL DEFAULT NULL COMMENT '年龄',
`gender` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '性别',
`province` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '籍贯',
`tuition` int(11) NULL DEFAULT NULL COMMENT '学费',
PRIMARY KEY (`sid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES (1, '王永', 23, '男', '北京', 1500);
INSERT INTO `student` VALUES (2, '张雷', 25, '男', '辽宁', 2500);
INSERT INTO `student` VALUES (3, '李强', 22, '男', '北京', 3500);
INSERT INTO `student` VALUES (4, '宋永合', 25, '男', '北京', 1500);
INSERT INTO `student` VALUES (5, '叙美丽', 23, '女', '北京', 1000);
INSERT INTO `student` VALUES (6, '陈宁', 22, '女', '山东', 2500);
INSERT INTO `student` VALUES (7, '王丽', 21, '女', '北京', 1600);
INSERT INTO `student` VALUES (8, '李永', 23, '男', '北京', 3500);
INSERT INTO `student` VALUES (9, '张玲', 23, '女', '广州', 2500);
INSERT INTO `student` VALUES (10, '啊历', 18, '男', '山西', 3500);
INSERT INTO `student` VALUES (11, '王刚', 23, '男', '湖北', 4500);
INSERT INTO `student` VALUES (12, '陈永', 24, '男', '北京', 1500);
INSERT INTO `student` VALUES (13, '李雷', 24, '男', '辽宁', 2500);
INSERT INTO `student` VALUES (14, '李沿', 22, '男', '北京', 3500);
INSERT INTO `student` VALUES (15, '王小明', 25, '男', '北京', 1500);
INSERT INTO `student` VALUES (16, '王小丽', 23, '女', '北京', 1000);
INSERT INTO `student` VALUES (17, '唐宁', 22, '女', '山东', 2500);
INSERT INTO `student` VALUES (18, '唐丽', 21, '女', '北京', 1600);
INSERT INTO `student` VALUES (19, '张永', 23, '男', '北京', 3500);
INSERT INTO `student` VALUES (20, '唐玲', 23, '女', '广州', 2500);
INSERT INTO `student` VALUES (21, '叙刚', 18, '男', '山西', 3500);
INSERT INTO `student` VALUES (22, '王累', 23, '男', '湖北', 4500);
INSERT INTO `student` VALUES (23, '赵安', 23, '男', '北京', 1500);
INSERT INTO `student` VALUES (24, '关雷', 25, '男', '辽宁', 2500);
INSERT INTO `student` VALUES (25, '李字', 22, '男', '北京', 3500);
INSERT INTO `student` VALUES (26, '叙安国', 25, '男', '北京', 1500);
INSERT INTO `student` VALUES (27, '陈浩难', 23, '女', '北京', 1000);
INSERT INTO `student` VALUES (28, '陈明', 22, '女', '山东', 2500);
INSERT INTO `student` VALUES (29, '孙丽', 21, '女', '北京', 1600);
INSERT INTO `student` VALUES (30, '李治国', 23, '男', '北京', 3500);
INSERT INTO `student` VALUES (31, '张娜', 23, '女', '广州', 2500);
INSERT INTO `student` VALUES (32, '安强', 18, '男', '山西', 3500);
INSERT INTO `student` VALUES (33, '王欢', 23, '男', '湖北', 4500);
INSERT INTO `student` VALUES (34, '周天乐', 23, '男', '北京', 1500);
INSERT INTO `student` VALUES (35, '关雷', 25, '男', '辽宁', 2500);
INSERT INTO `student` VALUES (36, '吴强', 22, '男', '北京', 3500);
INSERT INTO `student` VALUES (37, '吴合国', 25, '男', '北京', 1500);
INSERT INTO `student` VALUES (38, '正小和', 23, '女', '北京', 1000);
INSERT INTO `student` VALUES (39, '吴丽', 22, '女', '山东', 2500);
INSERT INTO `student` VALUES (40, '冯含', 21, '女', '北京', 1600);
INSERT INTO `student` VALUES (41, '陈冬', 23, '男', '北京', 3500);
INSERT INTO `student` VALUES (42, '关玲', 23, '女', '广州', 2500);
INSERT INTO `student` VALUES (43, '包利', 18, '男', '山西', 3500);
INSERT INTO `student` VALUES (44, '威刚', 23, '男', '湖北', 4500);
INSERT INTO `student` VALUES (45, '李永', 23, '男', '北京', 1500);
INSERT INTO `student` VALUES (46, '张关雷', 25, '男', '辽宁', 2500);
INSERT INTO `student` VALUES (47, '送小强', 22, '男', '北京', 3500);
INSERT INTO `student` VALUES (48, '关动林', 25, '男', '北京', 1500);
INSERT INTO `student` VALUES (49, '苏小哑', 23, '女', '北京', 1000);
INSERT INTO `student` VALUES (50, '赵宁', 22, '女', '山东', 2500);
INSERT INTO `student` VALUES (51, '陈丽', 21, '女', '北京', 1600);
INSERT INTO `student` VALUES (52, '钱小刚', 23, '男', '北京', 3500);
INSERT INTO `student` VALUES (53, '艾林', 23, '女', '广州', 2500);
INSERT INTO `student` VALUES (54, '郭林', 18, '男', '山西', 3500);
INSERT INTO `student` VALUES (55, '周制强', 23, '男', '湖北', 4500);
SET FOREIGN_KEY_CHECKS = 1;
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url= jdbc:mysql://localhost:3306/lanqiao?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=root
<configuration>
<typeAliases>
<package name="cn.lanqiao.pojo"/>
typeAliases>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="helperDialect" value="mysql"/>
plugin>
plugins>
configuration>
Lombok 是一个小工具 可以再编写实体的时候 自动帮助我们去生成构造方法 getter settter toString等一些可以使用idea自动生成的方法
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.12version>
dependency>
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
public class Student {
private Integer sid;
private String sname;
private Integer age;
private String gender;
private String province;
private Integer tuition;
}
使用lombok去构建一个pojo对象
public static void main(String[] args) {
Student student = Student.builder().sname("张三").age(22).gender("女").build();
System.out.println(student);
}
public interface StudentMapper {
//新增
int insertStudent(Student student);
//删除
int deleteStudentById(Integer sid);
//更新
int updadteStudent(Student student);
//查询单个学生
Student selectById(Integer sid);
//查询所有学生
List<Student> selectAll();
}
编写对应的 映射文件
<mapper namespace="cn.lanqiao.mapper.StudentMapper">
<insert id="insertStudent" parameterType="cn.lanqiao.pojo.Student">
insert into student(sname,age,gender,province,tuition) values(#{sname},#{age},#{gender},#{province},#{tuition})
insert>
<delete id="deleteStudentById" parameterType="int">
delete from student where sid=#{sid}
delete>
<update id="updadteStudent" parameterType="cn.lanqiao.pojo.Student">
update student set sname=#{sname},age=#{age},gender=#{gender},province=#{province},tuition=#{tuition}
where sid=#{sid}
update>
<select id="selectById" parameterType="int" resultType="cn.lanqiao.pojo.Student">
select * from student where sid=#{sid}
select>
<select id="selectAll" resultType="cn.lanqiao.pojo.Student" >
select * from student
select>
mapper>
注册映射文件在mybatis-config.xml
<mappers>
<package name="cn.lanqiao.mapper"/>
mappers>
public interface StudentService {
int addStudent(Student student);
int removeStduent(Integer sid);
int updateStudent(Student student);
Student queryStudent(Integer sid);
List<Student> queryAll();
}
service的实现
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Override
public int addStudent(Student student) {
return studentMapper.insertStudent(student);
}
@Override
public int removeStduent(Integer sid) {
return studentMapper.deleteStudentById(sid);
}
@Override
public int updateStudent(Student student) {
return studentMapper.updadteStudent(student);
}
@Override
public Student queryStudent(Integer sid) {
return studentMapper.selectById(sid);
}
@Override
public List<Student> queryAll() {
return studentMapper.selectAll();
}
}
spring-dao.xml
<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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
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/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:property-placeholder location="classpath*:database.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<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="10"/>
<property name="maxActive" value="30"/>
<property name="minIdle" value="5"/>
<property name="defaultAutoCommit" value="false"/>
<property name="maxWait" value="10000"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath*:mybatis-config.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory">property>
<property name="basePackage" value="cn.lanqiao.mapper"/>
bean>
beans>
spring-service.xml
<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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
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/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="cn.lanqiao.service"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
beans>
spring-mvc.xml
<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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
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/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="cn.lanqiao.controller"/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
bean>
<mvc:default-servlet-handler/>
beans>
spring配置文件的整合
<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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
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/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<import resource="classpath*:spring-*.xml"/>
beans>
配置web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath*:spring-*.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>*.dourl-pattern>
servlet-mapping>
<filter>
<filter-name>characterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>forceRequestEncodingparam-name>
<param-value>trueparam-value>
init-param>
<init-param>
<param-name>forceResponseEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>characterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<session-config>
<session-timeout>15session-timeout>
session-config>
web-app>
编写处理器
@Controller
@RequestMapping("/stu")
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping("/list")
public String list(Model model){
List<Student> list = studentService.queryAll();
model.addAttribute("list",list);
return "list";
}
}
list页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Title
学生信息列表
ID
姓名
年龄
性别
籍贯
学费
${student.sid}
${student.sname}
${student.age}
${student.gender}
${student.province}
${student.tuition}
首页
Hello World!
进入学生信息列表