用處:
一、自定義異常處理類,繼承Exception
package com.mingde.custom;
@SuppressWarnings("all")
public class CustomException extends Exception {
private String message;
public CustomException(String message) {
this.message=message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
二、實現全局異常處理功能(實現接口HandlerExceptionResolver)
package com.mingde.custom;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
public class CustomExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj,
Exception ex) {
CustomException ce;
//判斷ex異常類型是否爲CustomException,如果是就將其賦給CustomException對象,如果不是new一個未知異常
if(ex instanceof CustomException){
ce=(CustomException)ex;
}else{
ce=new CustomException("未知異常");
}
//將錯誤信息放入請求作用域中
request.setAttribute("message", ce.getMessage());
try {
//進行頁面的跳轉,跳轉到錯誤信息頁面
request.getRequestDispatcher("/WEB-INF/student/error.jsp").forward(request, response);
} catch (ServletException | IOException e) {
e.printStackTrace();
}
return new ModelAndView();
}
}
三、在SPringMVC.xml文件配置中配置上述該類、
<!-- 配置全局異常處理的javaBean,這樣DispatcherServlet就可以直接訪問他 -->
<bean class="com.mingde.custom.CustomExceptionResolver"></bean>
方式二:也可以在CustomExceptionResolver類前面使用@Component 註解;前提是springmvc.xml文件配置中得有註解掃描器,並且能掃描到該類
示例:在控制層中向上拋出異常
if("張三".equals(st.getSname())){
throw new CustomException("不能添加該名稱");
}