SpringMVC简单异常处理器SimpleMappingExceptionResolver的使用

在开发中我们经常需要统一处理异常

springMVC的异常处理流程:

简单异常处理,使用SimpleMappingExceptionResolver

在我项目中的注册功能需要有对用户名已经存在,密码格式不符合等作出反应。

我们先自定义一个异常,定义message属性用于存放异常的信息

package cn.hyit.oj.common.exception;

public class RegisterException extends Exception{
    @Override
    public String getMessage() {
        return message;
    }

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

    private String message;

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

在service层中抛出异常

 List<Users> usersList = usersMapper.selectByExample(example);
        if (usersList.size()>0)
            throw new RegisterException("用户名已经存在");
最后在springmvc配置文件中配置SimpleMappingExceptionResolver
<!-- springmvc提供的简单异常处理器 -->
	<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		<!-- 定义默认的异常处理页面 -->
		<property name="defaultErrorView" value="/WEB-INF/jsp/error.jsp"/>
		<!-- 定义异常处理页面用来获取异常信息的变量名,也可不定义,默认名为exception -->
		<property name="exceptionAttribute" value="ex" />
		<!-- 定义需要特殊处理的异常,这是重要点 -->
		<property name="exceptionMappings">
			<props>
				<prop key="cn.hyit.oj.common.exception.RegisterException">register</prop>
			</props>
			<!-- 还可以定义其他的自定义异常 -->
		</property>
	</bean>

我们在这里的exceptionMappings中定义一下当出现这个异常时候,跳转到哪个页面,这里我选择跳转到register这个页面。

最后在jsp中输出我们的错误信息

 <h1 class="text-center" style="margin-bottom: 30px">用户注册</h1>
                <center><h5 style="color:red">${ex.message}</h5></center>

ex是异常对象,在springmvc的exceptionAttribute中可配置名称,默认是exception。message是我们刚刚定义的异常信息的属性

最后效果如图


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值