SpringMVC_统一异常处理

用处:

我们只需在dao、service、controller层中向上抛出异常,则由DispatcherServlet接受到异常调用全局异常的处理方法进行处理

一、自定义异常处理类,继承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("不能添加该名称");
		}

发布了62 篇原创文章 · 获赞 9 · 访问量 3万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章