web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 声明,注册springmvc的核心对象DispatcherServlet-->
<servlet>
<servlet-name>myweb</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 自定义springmvc读取的配置文件的位置-->
<init-param>
<!--springmvc的配置文件属性-->
<param-name>contextConfigLocation</param-name>
<!-- 指定自定义文件的位置-->
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!-- 在tomcat启动后,创建Servlet对象
load-on-startup:表示tomcat启动后创建对象的顺序,它的值是正数,数值越小 tomacat创建对象越早
-->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 所有的*..do请求交给myweb中央处理器处理-->
<servlet-mapping>
<servlet-name>myweb</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!--注册声明过滤器,解决post请求乱码问题-->
<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>
<!--强制请求对象(HttpServletRequest)使用encoding编码的值-->
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<!--强制应答对象(HttpServletResponse)使用encoding编码的值-->
<init-param>
<param-name>forceReponsetEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<!--
/*:表示强制所有的请求先通过过滤器处理
-->
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
springmvc:
<?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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 用了注解需要注解扫描器:声明组件扫描器:包扫描-->
<context:component-scan base-package="com.bjpowernode.controller"/>
<!-- 声明springmvc框架中的视图解析器,帮助开发人员设置视图文件的路径-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀:视图文件的路径-->
<property name="prefix" value="/WEB-INF/view/"/>
<!-- 后缀:视图文件的扩展名-->
<property name="suffix" value=".jsp"/>
</bean>
<!--异常包注解扫描-->
<context:component-scan base-package="com.bjpowernode.handler"/>
<!--注解驱动-->
<mvc:annotation-driven/>
</beans>
新建异常类:
MyUserException:
package com.bjpowernode.exception;
public class MyUserException extends Exception {
public MyUserException() {
super();
}
public MyUserException(String message) {
super(message);
}
}
NameException:
package com.bjpowernode.exception;
//当用户的姓名有异常,抛出NameException
public class NameException extends MyUserException {
public NameException() {
super();
}
public NameException(String message) {
super(message);
}
}
AgeException:
package com.bjpowernode.exception;
//当年龄有问题,抛出的异常
public class AgeException extends MyUserException{
public AgeException() {
super();
}
public AgeException(String message) {
super(message);
}
}
MyController:
package com.bjpowernode.controller;
import com.bjpowernode.exception.AgeException;
import com.bjpowernode.exception.MyUserException;
import com.bjpowernode.exception.NameException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class MyController {
@RequestMapping(value = "/some.do")
public ModelAndView doForword(String name,Integer age) throws MyUserException {
//处理some.do请求了,相当于service调用处理完成了
ModelAndView mv=new ModelAndView();
//根据请求参数,抛出异常
//当姓名不是‘zs’时抛出异常
if (!"zs".equals(name)){
throw new NameException("姓名不正确!!");
}
if (age==null || age>80){
throw new AgeException("年龄比较大!!");
}
mv.addObject("myname",name);
mv.addObject("myage",age);
mv.setViewName("show");
return mv;
}
}
创建全局异常处理类:
GlobalExceptionHandler:
package com.bjpowernode.handler;
import com.bjpowernode.exception.AgeException;
import com.bjpowernode.exception.NameException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
/*
* @ControllerAdvice:控制器增强(也就是说给控制器增加功能--异常处理功能)
* 位置:在类的上面
* 特点:必须让框架知道这个注解所在的包名,需要在springmvc配置文件中声明组件扫描器
* 指定@ControllerAdvice所在的包名
* */
@ControllerAdvice
public class GlobalExceptionHandler {
//定义方法,处理发生的异常
/**
* 处理异常的方法和控制器方法的定义一样,可以有多个参数,可以有ModelAndView、
* String、void、多种对象类型的返回值
*
* 形参:Exception,表示Controller中抛出的异常对象。通过形参可以获取发生的异常信息
*
* @ExceptionHandler(异常的class):
* 表示异常的类型,当发生此类型异常时,由当前方法来处理,
*/
//处理NameException的异常
@ExceptionHandler(value = NameException.class)
public ModelAndView doNameException(Exception ex){
/*
异常发生处理逻辑:
1.需要把异常记录下来,记录到数据库,日志文件。
记录异常发生的是时间,那个方法发生的,异常错误类型
2.发送通知,把异常的信息通过邮件,短信,微信发送给相关人员。
3.给用户友好提示
*/
ModelAndView mv=new ModelAndView();
mv.addObject("msg","姓名必须为zs,其他用户不能访问!");
mv.addObject("ex",ex);
mv.setViewName("nameError");
return mv;
}
//处理AgeException
@ExceptionHandler(value = AgeException.class)
public ModelAndView doAgeException(Exception ex){
ModelAndView mv=new ModelAndView();
mv.addObject("msg","你的年龄不能大于80");
mv.addObject("ex",ex);
mv.setViewName("ageError");
return mv;
}
//处理其他异常,NameException,AgeException以外,不知类型的异常,不加value
@ExceptionHandler
public ModelAndView doOtherException(Exception ex){
ModelAndView mv=new ModelAndView();
mv.addObject("msg","发生其他异常");
mv.addObject("ex",ex);
mv.setViewName("defaultError");
return mv;
}
}
show.jsp:
<%--
Created by IntelliJ IDEA.
User: DELL
Date: 2022/6/7
Time: 19:01
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
<title>Title</title>
<base href="<%=basePath%>">
</head>
<body>
<h3>/WEB-INF/view/show.jsp.从request作用域获取数据</h3>
<h3>myname数据:${myname}</h3>
<h3>myage数据:${myage}</h3>
</body>
</html>
异常处理页面:
nameError.jsp:
<%--
Created by IntelliJ IDEA.
User: DELL
Date: 2022/6/24
Time: 16:22
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
<title>Title</title>
<base href="<%=basePath%>">
</head>
<body>
nameError.jsp<br>
提示信息:${msg}<br>
系统异常消息:${ex.message}
</body>
</html>
ageError.jsp:
<%--
Created by IntelliJ IDEA.
User: DELL
Date: 2022/6/24
Time: 16:22
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
<title>Title</title>
<base href="<%=basePath%>">
</head>
<body>
ageError.jsp<br>
提示信息:${msg}<br>
系统异常消息:${ex.message}
</body>
</html>
default.jsp:
<%--
Created by IntelliJ IDEA.
User: DELL
Date: 2022/6/24
Time: 16:22
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
<title>Title</title>
<base href="<%=basePath%>">
</head>
<body>
defaultError.jsp<br>
提示信息:${msg}<br>
系统异常消息:${ex.message}
</body>
</html>
index.jsp:
<%--
Created by IntelliJ IDEA.
User: DELL
Date: 2022/6/7
Time: 17:37
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
<title>Title</title>
<base href="<%=basePath%>">
</head>
<body>
<p>处理异常的,全局异常处理</p>
<form action="some.do" method="post">
姓名:<input type="text" name="name"><br>
年龄:<input type="text" name="age"><br>
<input type="submit" value="提交请求">
</form>
</body>
</html>
当输入格式正确时:
当姓名输入错误时:发生姓名异常
当输入年龄错误时:发生年龄异常
发生其他异常 :年龄输入abc: