프로그래밍/JSP Servlet

JSP/Servlet - jsp 페이지에서 에러 발생시 다른 페이지로 이동하기

가카리 2015. 12. 30. 21:58
반응형

 

jsp페이지에서 에러 페이지 호출하기 예제

 

 

 

Adder.jsp 페이지는 첫번째 페이지이고 DataError.jsp는 에러페이지입니다.

 

Adder.jsp

 

<%@ page language="java" contentType="text/html; charset=EUC-KR"

pageEncoding="EUC-KR"%>

<%

    int num1 = 0, num2 = 0, result = 0;

    try{

        String str1 = request.getParameter("NUM1");

        String str2 = request.getParameter("NUM2");

        num1 = Integer.parseInt(str1);//값이 숫자가 아니면 에러가

        num2 = Integer.parseInt(str2);

        result = num1 + num2;

    }

    catch(NumberFormatException e){

        RequestDispatcher dispatcher = request.getRequestDispatcher("DataError.jsp");

        dispatcher.forward(request, response);

    }

 

%>

<!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>

    <%= num1 %> + <%= num2 %> = <%= result %>

</body>

</html>

 

 

DataError.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>

    에러가 발생하였습니다.

</body>

</html>

 

출력화면

아래와 같이 파란색 부분에 변수를 정수로 제대로 넣어주면 에러가 발생하지 않는다.

 

아래와 같이 정수값이 아니면 에러페이지로 가게됩니다.

 

 

위의 Adder.jsp에서 try catch문을 지우고 바로 에러페이지로 가게하고 싶다면 다음과 같이 page지시자에 errorPage애트리뷰트를 쓰고 URL 경로명을 지정해놓으면 됩니다.

 

NewAdder.jsp

 

<%@ page language="java" contentType="text/html; charset=EUC-KR"

pageEncoding="EUC-KR" errorPage="DataError.jsp"%>

 

<%

    int num1 = 0, num2 = 0, result = 0;

        String str1 = request.getParameter("NUM1");

        String str2 = request.getParameter("NUM2");

        num1 = Integer.parseInt(str1);//값이 숫자가 아니면 에러가

        num2 = Integer.parseInt(str2);

        result = num1 + num2;

 

 

%>

<!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>

    <%= num1 %> + <%= num2 %> = <%= result %>

</body>

</html>

 

 

반응형