springmvc異常處理器


//編寫自定義異常類
package cn.bdqn.stusystem.util;

public class MyException extends Exception{

    private String message;

    public MyException(String message) {
        this.message = message;
    }

    public MyException() {
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
    
    
}

//實現異常處理器
package cn.bdqn.stusystem.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

public class MyHandleException implements HandlerExceptionResolver{

    @Override
    public ModelAndView resolveException(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,
            Exception arg3) {
        // 定義異常信息
                String msg;

                // 判斷異常類型
                if(arg3 instanceof MyException){
                    msg = arg3.getMessage();
                }else{
                    Writer writer = new StringWriter();
                    PrintWriter printWriter = new PrintWriter(writer);
                    arg3.printStackTrace(printWriter);
                    msg = writer.toString();
                }
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("msg", msg);
            modelAndView.setViewName("error");
            return modelAndView;
    }

}

//在springmvc中配置異常處理器
<bean id="myHandleException" class="cn.bdqn.stusystem.util.MyHandleException"></bean>

 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com