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是我们刚刚定义的异常信息的属性
最后效果如图
相关文章推荐
- SpringMVC 学习-异常处理 SimpleMappingExceptionResolver 类
- springmvc学习笔记(30)——SimpleMappingExceptionResolver异常映射
- SimpleMappingExceptionResolver的使用
- Spring MVC 全局异常处理(1) --SimpleMappingExceptionResolver
- Spring MVC中使用SimpleUrlHandlerMapping映射处理器的一个简单例子
- Spring MVC 全局异常处理(1) --SimpleMappingExceptionResolver
- SimpleMappingExceptionResolver的使用
- SimpleMappingExceptionResolver的使用方法
- Spring MVC 全局异常处理(1) --SimpleMappingExceptionResolver
- Spring MVC 全局异常处理(1) --SimpleMappingExceptionResolver
- 13.4、异常处理——SimpleMappingExceptionResolver
- SimpleMappingExceptionResolver的使用
- SimpleMappingExceptionResolver的使用
- 使用Spring中的ExceptionHandlerExceptionResolver进行统一的异常处理
- SpringMVC框架中的异常解析器-ExceptionHandler和HandlerExceptionResolver
- 【小平工作日志】Spring MVC异常处理SimpleMappingExceptionResolver详解!
- Spring MVC异常处理SimpleMappingExceptionResolver【转】
- SpringMVC框架中的异常解析器-ExceptionHandler和HandlerExceptionResolver(转)
- 使用Spring MVC HandlerExceptionResolver处理异常
- 使用Spring中的ExceptionHandlerExceptionResolver进行统一的异常