SpringMVC(五):springMVC异常处理

在浏览器访问服务器时,服务器端处理请求中出现异常后,如果直接抛出显示在浏览器页面上,客户的体验效果不是很好,因此,我们可以在出现异常时,自定义异常页面,使提高用户的体验效果。在springmvc中,给我们提供了三种处理异常的方式。

1、配置简单的异常处理器的方式

1.1、编写一个简单的异常页面error.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>异常页面</title>
</head>
<body style="font-size:30px;">
	系统繁忙,稍后再试!
</body>
</html>

1.2、配置异常处理

	<!--配置简单异常处理器  -->
	<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		<property name="exceptionMappings">
			<props>
				<prop key="java.lang.Exception">error</prop>
			</props>
		</property>
	</bean>

2、添加异常处理方法的方式

2.1、编写异常处理页面error.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>异常页面</title>
</head>
<body style="font-size:30px;">
	系统繁忙,稍后再试!
</body>
</html>

2.2、编写异常处理方法

	/**
	 * 异常处理方法,e:是其他方法所抛出的异常
	 * @description TODO
	 * @param e
	 * @param request
	 * @return
	 */
	@ExceptionHandler
	public String handleEx(Exception e,HttpServletRequest request) {
		return "error/error";
	}

3、自定义异常处理方法

3.1、自定义异常类

package com.wedu.springmvc.exception;

/**
 * 自定义异常类
 */
public class SysException extends Exception{

    // 存储提示信息的
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public SysException(String message) {
        this.message = message;
    }

}

3.2、自定义异常处理器

package com.wedu.springmvc.exception;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 异常处理器
 */
public class SysExceptionResolver implements HandlerExceptionResolver{

    /**
     * 处理异常业务逻辑
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @return
     */
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 获取到异常对象
        SysException e = null;
        if(ex instanceof SysException){
            e = (SysException)ex;
        }else{
            e = new SysException("系统正在维护....");
        }
        // 创建ModelAndView对象
        ModelAndView mv = new ModelAndView();
        mv.addObject("errorMsg",e.getMessage());
        mv.setViewName("error");
        return mv;
    }

}

3.3、配置异常处理器

    <!-- 配置异常处理器 -->
    <bean id="sysExceptionResolver" class="com.wedu.springmvc.exception.SysExceptionResolver"/>
发布了134 篇原创文章 · 获赞 10 · 访问量 7341

猜你喜欢

转载自blog.csdn.net/yu1755128147/article/details/103906586