본문 바로가기
HTML

Servlet 실습 3 (html code를 받아 서버에서 확인후 html 출력) 200,404,500

by aesup 2021. 3. 10.
728x90

index.html

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

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

HelloServlet

package hello;

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 {
		
		//html code 데이터를 html로 날려준다
		
		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>");
		
			pw.println("<h3>HelloServlet</h3>");
			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 {
		
	}

}

XML

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  <display-name>sample04</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
  	<servlet-name>hello</servlet-name>
  	<servlet-class>hello.HelloServlet</servlet-class>
  </servlet>
  	
  
  <servlet-mapping>
  	<servlet-name>hello</servlet-name>
  	<url-pattern>/hello</url-pattern>
  </servlet-mapping>
  
</web-app>
728x90