您的位置:首页 > 移动开发

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

2018-02-28 19:31 585 查看

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

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是我们刚刚定义的异常信息的属性
最后效果如图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息