[Servlet] 에러 처리(sendError) & URL 이동(sendRedirect)
앎/web 2014. 3. 7. 00:50 |에러 처리 (sendError)
에러 발생시 HttpServletResponse 클래스의 sendError 메서드를 사용하여 사용자에게 에러 페이지를 보여줄 수 있다.
Method |
||
void |
sendError(int sc) | Sends an error response to the client using the specified status code and clearing the buffer. |
void | sendError(int sc, String msg) | Sends an error response to the client using the specified status. |
응답 코드는 일반적으로 500번대의 서버 에러를 출력한다.
예제)
web.xml
.... <servlet> <servlet-name>CalcServlet</servlet-name> <servlet-class>com.study.CalcServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CalcServlet</servlet-name> <url-pattern>/calc.do</url-pattern> </servlet-mapping> ....
calcPare.htm
<!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>sendError 테스트</title> </head> <body> <form name="myForm" method="post" action="/SendErrorTest/calc.do"> 값1 = <input type="text" name="val1"/><br/> 값2 = <input type="text" name="val2"/><br/> <input type="submit" value="계산"/> </form> </body> </html>
CalcServlet.java
package com.study; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CalcServlet extends HttpServlet { public void init() { } public void service(HttpServletRequest _request, HttpServletResponse _response) throws IOException, ServletException { String val1 = _request.getParameter("val1"); String val2 = _request.getParameter("val2"); try { int iVal1 = Integer.parseInt(val1); int iVal2 = Integer.parseInt(val2); System.out.println("합: " + (iVal1 + iVal2)); } catch(Exception _ex) { _response.sendError(588, "숫자로 변환할 수 없는 데이터가 입력되었습니다."); } } public void destroy() { } }
입력 폼에서 숫자가 아닌 문자를 입력하고 '계산' 버튼을 누르면 예외 처리로 빠지게 되어 다음과 같은 오류 페이지가 나타난다.
예외 처리 시 설정한 에러 코드와 메시지가 보일 것이다.
URL 이동 (sendRedirect)
HttpServletResponse 클래스의 sendRedirect 메서드로 특정 URL이나 페이지로 이동할 수 있다.
이동 시 현재 페이지까지 전달된 request의 파라미터는 리셋되고 웹 브라우저의 URL도 이동하는 경로로 변경된다.
앞서 작성한 CalcServlet.java 내에 try 마지막 부분에 다음 내용을 추가한다.
계산이 완료된 후 successPage.htm 페이지로 이동하라는 의미이다.
_response.sendRedirect("successPage.htm");
successPage.htm
<!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>sendRedirect 테스트</title> </head> <body> <center> 계산이 완료되었습니다.</center> </body> </html>
계산이 완료되면 다음과 같이 페이지가 이동하게 된다.
'앎 > web' 카테고리의 다른 글
[Servlet] 웹에서의 데이터 저장 (데이터 저장 영역: request, session, application) (1) | 2014.03.07 |
---|---|
[Servlet] RequestDispatcher 인터페이스 (0) | 2014.03.07 |
[Servlet] 초기화 매개변수 (0) | 2014.03.06 |
[Servlet] GET, POST 방식 요청시 한글 처리 (0) | 2014.03.06 |
[Servlet] 웹 페이지에서의 데이터 요청 방식 (GET, POST) (0) | 2014.03.06 |