Spring - Exception Handling Example
이번 강좌는 controller내부에서 발생하는 하나 또는 그 이상의 예외(exception을 다룰 수 있는 Spring MVC framework를 이용하여 간단한 웹기반 프로그램을 작성하는 법을 알아본다.
[21-1] 강좌를 참고하여 프로젝트를 생성한다.
Student.java :
package com.tutorialspoint.hellowebexception;
public class Student {
private Integer age;
private String name;
private Integer id;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
SpringException.java :
package com.tutorialspoint.hellowebexception;
public class SpringException extends RuntimeException {
private String exceptionMsg;
public SpringException(String exceptionMsg) {
super();
this.exceptionMsg = exceptionMsg;
}
public String getExceptionMsg() {
return exceptionMsg;
}
public void setExceptionMsg(String exceptionMsg) {
this.exceptionMsg = exceptionMsg;
}
}
StudentController.java : 여기서 다루어질 하나 또는 그이상의 예외를 명시할 수 있는 '@ExecptionHanlder'를 사용하여 service method를 annotate해야한다. 만약 하나이상의 예외를 명시하려면 comma(,)로 값을 구분할 수 있다.
package com.tutorialspoint.hellowebexception;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class StudentController {
@RequestMapping(value="/student", method=RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("student", "command", new Student());
}
@RequestMapping(value="/addStudent", method=RequestMethod.POST)
@ExceptionHandler({SpringException.class})
public String addStudent(@ModelAttribute("HelloWeb")Student student, ModelMap model) {
if(student.getName().length() < 5) {
throw new SpringException("Given name is too short");
} else {
model.addAttribute("name", student.getName());
}
if(student.getAge() < 10) {
throw new SpringException("Given age is too low");
} else {
model.addAttribute("age", student.getAge());
}
model.addAttribute("id", student.getId());
return "result";
}
}
servlet-context.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.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.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<beans:bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<beans:property name="exceptionMappings">
<beans:props>
<beans:prop key="com.tutorialspoint.hellowebexception.SpringException">
ExceptionPage
</beans:prop>
</beans:props>
</beans:property>
<beans:property name="defaultErrorView" value="error"/>
</beans:bean>
<context:component-scan base-package="com.tutorialspoint.hellowebexception" />
</beans:beans>
student.jsp :
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Exception Handling</title>
</head>
<body>
<h2>Student Information</h2>
<form:form method="POST" action="/hellowebexception/addStudent">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td><form:label path="age">Age</form:label></td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td><form:label path="id">id</form:label></td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
error.jsp :
<html>
<head>
<title>Spring Error Page</title>
</head>
<body>
<p>An error occured, please contact webmaster.</p>
</body>
</html>
ExceptionPage.jsp : 여기서는 ${excption}을 통해 예외 인스턴스를 접근할 것이다.
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Exception Handling</title>
</head>
<body>
<h2>Spring MVC Exception Handling</h2>
<h3>${exception.exceptionMsg}</h3>
</body>
</html>
result.jsp :
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
<tr>
<td>ID</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>
실행 결과는 아래와 같다.