例外処理

14864 ワード

XMLと構文は例外処理の方法として使用できます.

Annotationベース


LoginController
ログイン時、IDがnullまたは入力値がない場合はエラーとして処理します.

ログイン名が空白の場合、エラーページが表示されます.
しかし、セキュリティ面では、内部情報の表示はよくありません.

ネームスペース-mvcの追加


例外処理クラスが作成され、例外のタイプに応じて適切な例外画面が提供されます.
CommonExceptionHandler
package com.springbook.view.common;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

// "com.springbook.view" 패키지 아래에서 일어나는 예외를 처리한다.
@ControllerAdvice("com.springbook.view")
public class CommonExceptionHandler {
	
	@ExceptionHandler(ArithmeticException.class)
	public ModelAndView handlerArithmeticException(Exception e) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("exception",e);
		mav.setViewName("/common/arithmeticError.jsp");
		return mav;
	}
	
	@ExceptionHandler(NullPointerException.class)
	public ModelAndView handleNullPointerException(Exception e) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("exception",e);
		mav.setViewName("/common/nullPointerError.jsp");
		return mav;
	}
	
	@ExceptionHandler(Exception.class)
	public ModelAndView handleException(Exception e) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("exception",e);
		mav.setViewName("/common/error.jsp");
		return mav;
	}
	
	
}
例外についての画面を作成します.
Error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page isErrorPage="true" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>기본 에러 화면</title>
</head>
<body bgcolor="#ffffff" text="#000000">
	<!-- 타이틀 시작 -->
	<table width="100%" border="1" cellspacing="0" cellpadding="0">
		<tr>
			<td align="center" bgcolor="orange">
				<b>기본 에러 화면입니다</b>
			</td>
		</tr>
	</table>
	<br>
	<!-- 에러 메시지 -->
	<table width="100%" border="1" cellspacing="0" cellpadding="0" align="center">
		<tr>
			<td align="center">
				<br><br><br><br><br>
                // e (exception) 안의 getmessage라는 메서드를 호출한 것.
				Message : ${exception.message }
				<br><br><br><br><br>
			</td>
		</tr>
	</table>
</body>
</html>

画面

XMLベース


xmlファイルに設定コードを追加する