자바스크립트에 있는 isNaN함수(숫자일때 참, 문자일때 거짓)를 JSP에서도 사용가능하게 하는 함수입니다.
public static boolean isNaN(String str) {
boolean check = true;
for(int i = 0; i < str.length(); i++) {
if(!Character.isDigit(str.charAt(i)))
{
check = false;
break;
} // end if
} //end for
return check;
} //isNaN
이 내용을 찾게 된 계기가 수업 중에 숫자를 입력하는 부분에서 문자를 입력했을 때 나오는 오류 처리 부분에서 발생했습니다.
AdderInput.html
<!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>Insert title here</title> </head> <body> <p align="center"> <form action="Adder.jsp" method="post"> 첫 번째 수 : <input type="text" name="num1"><br><br> 두 번째 수 : <input type="text" name="num2"><br><br> <input type="submit" value="더하기"> </form> </body> </html>
Adder.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>Insert title here</title>
</head>
<body>
<%
String n1 = request.getParameter("num1");
String n2 = request.getParameter("num2");
int num1 = Integer.parseInt(n1);
int num2 = Integer.parseInt(n2);
int num3 = num1 + num2;
out.println(num1 + "와" + num2 + "의 합은 " + num3 + "입니다.");
%>
</body>
</html>
AdderInput 페이지에서 숫자 값을 받아서 Adder 페이지에서 덧셈한 후 결과 값이 나오는 부분입니다.
여기서 문제는 AdderInput 페이지에서 문자를 입력했을 때 오류가 발생하는 점이었습니다.
오류 메시지를 보니 java.lang.NumberFormatException라는 예외 처리를 하라고 나와 있었습니다.
try catch문을 사용하여 예외 처리를 하였습니다.
Adder.jsp 수정01
<%@ 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>Insert title here</title>
</head>
<body>
<%
String n1 = request.getParameter("num1");
String n2 = request.getParameter("num2");
try {
int num1 = Integer.parseInt(n1);
int num2 = Integer.parseInt(n2);
int num3 = num1 + num2;
out.println(num1 + "와" + num2 + "의 합은 " + num3 + "입니다.");
} catch(NumberFormatException e) {
out.println(e.getMessage());
}
%>
</body>
</html>
catch 부분에 오류 메시지를 “?는 입력하실 수 없는 문자입니다.”라고 출력하고 싶어서 고민해본 결과,
if문으로 문자와 숫자를 구별하여 문자가 나오면 출력할 수 없다는 메시지를 출력하면 되겠구나 생각했습니다.
하지만 숫자일 때 참이고 문자일 때 거짓으로 나오게 하는 건 자바스크립트의 isNaN() 함수만 기억이 났다.
구글에서 isNaN 함수와 비슷한걸 찾아냈다. 포스팅 맨 위에 적혀있는 함수가 그 함수이다.
위의 함수를 사용하여 다시 고쳐 보았다.
Adder.jsp 수정02
<%@ 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>Insert title here</title>
</head>
<body>
<%!
public static boolean isNaN(String str) {
boolean check = true;
for(int i = 0; i < str.length(); i++) {
if(!Character.isDigit(str.charAt(i)))
{
check = false;
break;
} // end if
} //end for
return check;
} //isNaN
%>
<%
String n1 = request.getParameter("num1");
String n2 = request.getParameter("num2");
try {
int num1 = Integer.parseInt(n1);
int num2 = Integer.parseInt(n2);
int num3 = num1 + num2;
out.println(num1 + "와" + num2 + "의 합은 " + num3 + "입니다.");
} catch(NumberFormatException e) {
if(!isNaN(n1)) {
out.println(n1 + "는 입력하실 수 없는 문자입니다.");
}
if(!isNaN(n2)) {
out.println(n2 + "는 입력하실 수 없는 문자입니다.");
}
}
%>
</body>
</html>
이렇게 하고 능력자분께 자문했더니 try catch문을 사용할 필요가 없다고 하여 고민고민해본 결과 아래의 결과가 나왔다.
Adder.jsp 수정03
<%@ 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>Insert title here</title>
</head>
<body>
<%!public static boolean isNaN(String str) {
boolean check = true;
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
check = false;
break;
} // end if
} //end for
return check;
} //isNaN%>
<%
String n1 = request.getParameter("num1");
String n2 = request.getParameter("num2");
if (!isNaN(n1)) {
out.println(n1 + "는 입력하실 수 없는 문자입니다.");
} else if (!isNaN(n2)) {
out.println(n2 + "는 입력하실 수 없는 문자입니다.");
} else {
out.println(n1 + "와" + n2 + "의 합은 "
+ (Integer.parseInt(n1) + Integer.parseInt(n2))
+ "입니다.");
}
%>
</body>
</html>
마지막 else 부분에 덧셈하는 부분만 형변환으로 처리하면 굳이 예외처리를 할 필요가 없었던 거였다.
int ↔ String 형변환
1) int → Sting
String s = “0”;
int i = Integer.parseInt(s);2) String → int
int i = 0;
String s = Integer.toString(i);
Leave a Reply 응답 취소