본문 바로가기

개발/JAVA

[Servlet] #04. 예제 :: Error 페이지 전송하기 resp.sendError();

 

● 에러 출력

Console 상태

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<a href="hello?name='성춘향'">Hello Servlet move </a>
<br>

<h1> 상태 코드 확인 </h1>


<form action="hello" method="get">

<table>
<tr>
	<td> 상태 코드 </td>
	<td>
			<select name="code">
				<option value="200">SC_OK</option>
				<option value="404">SC_NOT_FOUND</option>
				<option value="500">SC_INTERNAL_SERVER_ERROR</option>	
			</select>
	</td>
</tr>
</table>
<input type="submit" value="송신">

</form>
 

</body>
</html>

 

package sample04;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("HelloServlet doGet");
		
	//	String name = req.getParameter("name");
	//	System.out.println("name:" + name);
		
		resp.setContentType("text/html; charset=utf-8");		
		PrintWriter pw = resp.getWriter();		
		pw.println("<html>");
		pw.println("<head>");
		pw.println("<title>제목</title>");
		pw.println("</head>");		
		pw.println("<body>");
		
		String code = req.getParameter("code");
		
		if(code.equals("200")) {
			pw.println("<p>200:SC_OK</p>");
		}
		else {
			if(code.equals("404")) {
				resp.sendError(HttpServletResponse.SC_NOT_FOUND, "못 찾겠다는 에러입니다");
			}
			else if(code.equals("500")) {
				resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "코드가 틀렸다는 에러입니다");
			}			
		}		
		
		pw.println("</body>");		
		pw.println("</html>");		
		
		pw.close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

	}	
}

 

● 다음 코드를 통해 에러 페이지를 출력할 수 있다.

resp.sendError(HttpServletResponse.SC_NOT_FOUND, "못 찾겠다는 에러입니다");

resp.sendError(HttpServletResponse.SC_NOT_FOUNDresp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "코드가 틀렸다는 에러입니다");