1.自定义一个异常类
public class CustomException extends Exception
{
private String message;
@Override
public String getMessage()
{
return message;
}
public void setMessage(String message)
{
this.message = message;
}
public CustomException(String message)
{
this.message = message;
}
public CustomException()
{
}
public CustomException(String message, String message1)
{
super(message);
this.message = message1;
}
}
2.自定一个异常处理器。
a.当springMvc发生异常时会执行这个异常处理器。
b.自定义异常处理器,实现 HandlerExceptionResolver 接口
public class CustomExceptionResolver implements HandlerExceptionResolver
{
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse
httpServletResponse, Object o, Exception e)
{
ModelAndView modelAndView = new ModelAndView();
CustomException customException;
if( e instanceof CustomException ){
customException=(CustomException) e;
}else {
customException=new CustomException("服务器正在维护...");
}
modelAndView.setViewName("error");
modelAndView.addObject("errorMsg",customException);
return modelAndView;
}
}
3.把自定义的异常处理器注入容器中。
a.在springmvc.xml配置
<!--
自定义异常处理器
-->
<bean id="customExceptionResolver" class="com.geor.hellSpringMvcXml.resolver.CustomExceptionResolver"></bean>
b. 或使用注解在自定义的异常处理器 类上加
@Component(“xxx”) 标签