SpringMVC處理自定義異常,經過讀取配置文件把錯誤信息顯示在前臺頁面

首先引入jar包,用於讀取配置資源文件:app

<!-- commons組件讀取配置文件相關依賴 -->
    <dependency>
        <groupId>commons-configuration</groupId>
        <artifactId>commons-configuration</artifactId>
        <version>1.8</version>
    </dependency>ide

自定義異常:工具

public class DuplicateException extends RuntimeException{
    private static final long serialVersionUID = 1L;
    public DuplicateException() {
    }
    public DuplicateException(String message){
        super(message);
    }
}測試

利用控制器通知註解@ControllerAdvice將自定義異常集中在同一個地方處理:spa

/**
 * 帶有@ControllerAdvice的類中,全部帶有@ExceptionHandler的方法會應用到
 * 整個應用程序全部控制器中帶有@RequestMapping註解的方法上
 * 註解@ControllerAdvice自己已經使用了@Component註解
 * @author dai
 *
 */
@ControllerAdvice
public class AppWideExceptionHandler {
    @ExceptionHandler(DuplicateException.class)
    public String duplicateHandler(HttpServletRequest request,DuplicateException ex){
        request.setAttribute("error", ex.getMessage());
        return "error/duplicate";
    }
}資源

控制器方法拋出自定義異常:get

@RequestMapping(value="/register",method=POST)
    public String processRegistration(Spitter spitter) throws IOException{
        if("test".equals(spitter.getUsername())){
            throw new DuplicateException(getProperty("username.duplicate"));
        }
        return "redirect:/spitter/"+spitter.getUsername();
    }it

此處用到的自定義錯誤提示,是經過讀取property配置文件來得到。io

getProperty()方法是本身封裝好的,以下:class

public class PropertiesUtil {
    private static PropertiesConfiguration configuration = null;
    public static String getProperty(String key){
        try {
            configuration = new PropertiesConfiguration("/spittr/props/errors.properties");
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
        return configuration.getString(key);
        
    }
    
}

該工具類利用了Commons組件包,/spittr/props/errors.properties爲資源文件的項目類加載路徑,注意:

commons-configuration組件拋出的ConfigurationException異常引用了commons-lang-2.6.jar包,因此commons-lang jar包的版本不能過高,這裏用的是2.6版本,測試能夠經過。

errors.properties定義以下:

username.duplicate=用戶名重複!

前臺JSP相關代碼:

This is an error page! <br />
error:<c:out value="${error}"></c:out>

項目運行後,在前臺表單輸入用戶名"test",提交後跳轉到錯誤提示頁面,並顯示用戶名重複!

參考資料:《Spring實戰(第4版)》

相關文章
相關標籤/搜索