1. 어노테이션 기반의 예외 처리 : @ControllerAdvice / @ExceptionHandler
- 스프링 설정 파일 (presentation-layer.xml) 수정 : <mvc:annotation-driven /> 추가
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<!-- Controller 클래스들이 들어있는 상위 패키지 -->
<context:component-scan base-package="com.springbook.view">
</context:component-scan>
<!-- 예외 처리 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 파일 업로드 설정 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000"></property>
</bean>
</beans>
- 예외 처리 클래스 작성 (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;
@ControllerAdvice("com.springbook.view")
//CommonsExceptionHandler 객체 자동 생성
//com.springbook.view 패키지로 시작하는 컨트롤러에서 예외가 발생하는 순간 하위에 @ExceptionHandler 어노테이션으로 지정한 메소드가 실행
public class CommonExceptionHandler {
@ExceptionHandler(ArithmeticException.class)
public ModelAndView handleArithmeticException(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;
}
}
- 예외 발생시 사용자에게 전송할 JSP 화면 작성 (error.jsp / arithmeticError.jsp / nullPointerError.jsp)
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<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 />
Message : ${exception.message }
<br /><br /><br /><br /><br />
</td>
</tr>
</table>
</body>
</html>
- LoginController에 예외 발생 코드 작성하여 테스트 (id가 null이거나 공백일 경우 예외 발생)
package com.springbook.view.user;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.springbook.biz.user.UserVO;
import com.springbook.biz.user.impl.UserDAO;
@Controller
public class LoginController {
@RequestMapping(value="/login.do", method=RequestMethod.POST)
public String login(UserVO vo, UserDAO userDAO, HttpSession session) {
if(vo.getId() == null || vo.getId().equals("")) {
throw new IllegalArgumentException("아이디는 반드시 입력해야 합니다.");
}
UserVO user = userDAO.getUser(vo); //DB에 회원 등록
if(user != null) {
session.setAttribute("userName", user.getName()); //사용자 이름을 session에 저장
return "getBoardList.do";
} else {
return "login.jsp";
}
}
}
2. XML 기반의 예외 처리
: 어노테이션 기반의 예외 처리 방식과는 다르게 예외 처리 클래스(CommonExceptionHandler)를 별도로 구현하지 않아도 됨 (예외 발생 JSP 화면은 당연 필요)
- 스프링 설정 파일(presentation-layer.xml) 수정 (SimpleMappingExceptionResolver 클래스를 <bean> 등록)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<!-- Controller 클래스들이 들어있는 상위 패키지 -->
<context:component-scan base-package="com.springbook.view">
</context:component-scan>
<!-- 파일 업로드 설정 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000"></property>
</bean>
<!-- 예외 처리 설정 -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.ArithmeticException">
common/arithmeticError.jsp
</prop>
<prop key="java.lang.NullPointerException">
common/nullPointerError.jsp
</prop>
</props>
</property>
<property name="defaultErrorView" value="common/error.jsp" />
</bean>
</beans>
'Spring > 7. Spring MVC' 카테고리의 다른 글
Day 73 : 파일 업로드 처리 (0) | 2022.01.27 |
---|---|
Day 73 : 검색 기능 추가 구현 (0) | 2022.01.27 |
Day 72 : 기타 어노테이션 (0) | 2022.01.26 |
Day 72 : 어노테이션으로 게시판 프로그램 구현 (0) | 2022.01.26 |
Day 72 : 어노테이션 기반 MVC 개발 (0) | 2022.01.26 |