继承HandlerExceptionResolver自定义异常处理器
控制器ExceptionController.java
package com.orange.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.orange.exception.NameException;
import com.orange.exception.PasswordException;
@Controller
@RequestMapping("/exception")
public class ExceptionController {
@RequestMapping("handlerException")
public ModelAndView doException2(String name, String password, ModelAndView mav) throws Exception{
if(! "admin".equals(name)){
throw new NameException("用户名错误");
}
if(! "admin".equals(password)){
throw new PasswordException("密码错误");
}
mav.addObject("name", name);
mav.addObject("password", password);
mav.setViewName("/showException.jsp");
return mav;
}
}
定义两个异常类型,NameException.Java和PasswordException.java
package com.orange.exception;
public class NameException extends Exception {
public NameException() {
super();
}
public NameException(String message) {
super(message);
}
}
package com.orange.exception;
public class PasswordException extends Exception {
public PasswordException() {
super();
}
public PasswordException(String message) {
super(message);
}
}
自定义异常处理器MyException,当发生异常时,指定跳转的视图jsp
package com.orange.exception;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import com.fasterxml.jackson.core.sym.Name;
public class MyExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
ModelAndView mav = new ModelAndView();
mav.addObject("ex", ex);
mav.setViewName("/defaultException.jsp");
if(ex instanceof NameException){
mav.setViewName("/showException.jsp");
}
if(ex instanceof PasswordException){
mav.setViewName("/showException.jsp");
}
return mav;
}
}
注册异常处理器
当发生异常时,跳转的jsp页面
exception.jsp
<%@ page language="java" contentType="text/html; charset=GBK"
pageEncoding="GBK"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
Default Page
SimpleMappingExceptionResolver
测试
HandlerExceptionResolver
showException.jsp
<%@ page language="java" contentType="text/html; charset=GBK"
pageEncoding="GBK"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
ShowExceptionPage
注:此段代码源自于博客园的愤怒的绿萝用户,如有侵权请联系