본문 바로가기

JSP 웹 프로그래밍/수업내용

[JSP 웹 프로그래밍] reponse 내장 객체

response 내장 객체

 - 사용자의 요청을 처리한 결과를 서버에서 웹 브라우저로 전달하는 정보를 저장하고 서버는 응답 헤더와 요청 처리 결과 데이터를 웹 브라우저로 보냄

 - JSP 컨테이너는 서버에서 웹 브라우저로 응답하는 정보를 처리하기 위해 javax.servlet.http.HttpServletResponse 객체 타입의 response 내장 객체를 사용하여 사용자의 요청에 응답

 

 

페이지 이동 관련 메소드

페이지 이동 = 리다이렉션(redirection)

   - 사용자가 새로운 페이지를 요청할 때와 같이 페이지를 강제로 이동하는
서버는 웹 브라우저에 다른 페이지로 강제 이동하도록 response 내장 객체의 리다이렉션 메소드를 제공

페이지 이동 시에는 문자 인코딩을 알맞게 설정해야

 

페이지 이동 관련 메소드의 종류

 

예제 1 [ 페이지 이동하기 ]

 - 해당 아이디로 입력하면 메인 화면으로 가고 아이디, 비밀번호가 맞지 않으면 다시 입력하는 화면 나오기

더보기
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
	<!-- 폼페이지 
	get : select(DB변경X)
	post : insert, update, delete(DB변경 O)
	
	요청 URI : /ch05/response01_process.jsp
	요청 파라미터 : request{id = a001, passwd = java}
	요청방식 : post
	 -->
	<form action="/ch05/response01_process.jsp" mathod="post">
		<P>아 이 디 : <input type="text" name="id" required placeholder="아이디" alt="아이디" title="아이디"/></P>
		<P>비밀번호 : <input type="text" name="passwd" placeholder="비밀번호" alt="비밀번호" title="비밀번호"/></P>
		<P><input type="submit" value="전송"/></P>
	
	</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Implicit Object</title>
</head>
<body>
	<!-- 
	response01_process.jsp
	요청 URI : /ch05/response01_process.jsp
	요청 파라미터 : request{id = a001, passwd = java}
	요청방식 : post
	 -->
	<%
		request.setCharacterEncoding("UTF-8");
	
		String userId = request.getParameter("id");
		String password = request.getParameter("passwd");
	
	%>
	
	<p><%=userId %></p>
	<p><%=password %></p>
	<%
		if(userId.equals("a001") && password.equals("java")){
			response.sendRedirect("/Welcome.jsp");
		}else {
			response.sendRedirect("/ch05/response01.jsp");
		}
	%>
</body>
</html>

 

결과 


응답 HTTP 헤더 관련 메소드

응답 HTTP 헤더 관련 메소드는 서버가 웹 브라우저에 응답하는 정보에 헤더를 축가하는 기능을 제공 

헤더 정보에는 주로 서버에 대한 정보가 저장되어 있음

응답 HTTP 헤더 관련 메소드의 종류

 

예제1  [ 응답 HTTP 헤더에 정보 추가하기]

더보기
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@page import="java.util.Enumeration"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
	<!-- 폼 페이지
	요청 URI : request01_process.jsp
	요청파라미터 : {id : a001, passwd : java}
	요청방식 : post
	 -->
	 <%
	 	//문자 인코딩 유형 (한글처리)
	   	request.setCharacterEncoding("UTF-8");
	 	// request 내장 객체로 전달된 요청 파라미터 정보를 받음 
		String userId = request.getParameter("id"); //a001
		String Password = request.getParameter("passwd");//java 
	 %>
	 <!-- 표현문 -->
	 <p>아이디 : <%=userId%></p>
	 <p>비밀번호 : <%=Password%></p>
	 <!-- 
	  웹 브라우저는 HTTP 헤더에 부가 정보를 담아서 서버로 전송함. 
	  request 내장 객체를 통해 헤더 정보, 쿠키 관련 정보를 얻을 수 있음. 
	  -->
	  <!--  -->
	  <%
	   	String hostValue = request.getHeader("host");
	  	String alvalue = request.getHeader("accept-language");
	  	String clvalue = request.getHeader("content-langth");
	  %>
		<p><%=hostValue %></p>
		<p><%=alvalue %></p>
		<p><%=clvalue%></p>
		<hr />
		<%
								//모든 헤더 이름을 가져옴 
			//리턴타입 : 열거형
			Enumeration en = request.getHeaderNames();
			//저장된 헤어 이름이 있을 때 가지 반복 
			while(en.hasMoreElements()){
				//현재 헤더 이름을 가져옴 (Object -> String downcasting)
				String headerName = (String)en.nextElement();
				//request.getHeader("host") -localhost
				String headerValue = request.getHeader(headerName);
				//				host      	  :     localhost
				out.print("<h3>"+headerName+" : " +headerValue+"</h3>");
			}
		%>
		<hr />
		<!-- 웹 브라우저 / 서버관련 메소드를 사용해 보자 -->
		<p>IP주소 : <%=request.getRemoteAddr() %></p>
		<p>요청 파라미터 길이 : <%=request.getContentLength() %></p>
		<p>문자 인코딩 : <%=request.getCharacterEncoding() %></p>
		<p>콘텐츠 유형(MIME) : <%=request.getContentType() %></p>
		<p>요청 프로토콜 : <%=request.getProtocol() %></p>
		<p>요청메소드 : <%=request.getMethod() %></p>
		<p>요청 URI 경로 :<%=request.getRequestURI() %></p>
		<P>contextPath : <%=request.getContextPath() %></P>
		<P>서버 이름 : <%=request.getServerName() %></P>
		<P>서버 포트번호 : <%=request.getServerPort() %></P>
		<P>쿼리스트링(요청파리미터) : <%=request.getQueryString() %></P>
		
		<%
			//새로운 URL로 재요청
			response.sendRedirect("/Welcome.jsp");
			
		
		%>
</body>
</html>

 

 

 

예제 2 [ 5초 마다 JSP페이지 갱신하기]

  - 특정 시간 이후 해당 홈페이지 새로고침 

더보기
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Implicit Objects</title>
</head>
<body>
	<p>이 페이지는 5초마다 새로고침 됩니다.</p>
	<%
		//response 내장 객체
		/*서버(톰켓) → 응답 → 클라이언트(크롬)
			MIME 유형, 문자 인코딩, 오류메시지(404, 500),
			상태코드를 설정 및 가져올 수 있음 
		*/
		//현재 문서에 대한 설정 
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		response.setIntHeader("Refresh", 5);
		
	%>
	<p><%=new Date() %></p>
	<p>문자 인코딩 : <%=response.getCharacterEncoding() %></p>
	<p>콘텐츠 유형 : <%=response.getContentType() %></p>
</body>
</html>

결과 


응답 콘텐츠 관련 메소드

- response 내장 객체는 웹 브라우저로 응답하기 위해 MIME 유형, 문자 인코딩, 오류 메시지, 상태 코드 등을 설정하고 가져오는 응답 콘텐츠 관련 메소드 제공 

 

응답 콘텐츠 관련 메소드의 종류

 

예제 [ 오류응답 코드와 오류메시지 보내기 ] 

 - 임의로 에러 발생 하기 

더보기
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Implicit Objects</title>
</head>
<body>
	<%
	
		response.sendError(404, "요청페이지를 찾을 수 없습니다.");
	
	%>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Implicit Objects</title>
</head>
<body>
	<%
	
		response.sendError(500, "개발자 오류");
	
	%>
</body>
</html>

 


out 내장 객체

-  브라우저(ex.크롬)데이터를 전송하는 출력 스트림 객체

-   JSP 컨테이너JSP 페이지에 사용되는 모든 표현문 태그(${})HTML, 일반 텍스트 등을 out 내장 객체를 통해

    웹 브라우저에 그대로 전달

-  스크립틀릿 태그에 사용하여 단순히 값을 출력하는 표현문 태그(<%= …%>)와 같은 결과를 얻을 수 있음

out 내장 객체 메소드의 종류

예제 1 [ 오늘의 날짜, 시간 출력하기 ]

더보기
<%@page import="java.util.Calendar"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Implicit Objects</title>
</head>
<body>
	<%
		out.print("오늘의 날짜 및 시간 : <br />");
		out.print("<p>" + Calendar.getInstance().getTime() + "</p>");
	%>
</body>
</html>

예제 2 [ 폼페이지에서 아이디와 비밀번호를 입력 받아 출력하기 ]

더보기

out02.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Implicit Objects</title>
</head>
<body>
	<form action="out02_process.jsp" method="post">
		<!--  required :  필수 입력 -->
		<P>아이디 : <input type="text" name="id" placeholder="아이디" required/></P>
		<P>비밀번호 : <input type="password" name="passwd" placeholder="비밀번호" required/></P>
		<!-- submit(기본) / button / reset -->
		<p><button type="submit">전송</button></p>
	</form>
</body>
</html>

 

response01_process.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Implicit Objects</title>
</head>
<body>
	<!-- 
		요청 URL : out02_process.jsp
		요청파라미터(HTTP파라미터, QueryString) : request {id : admin, passwd=java}
		요청방식 :post
	 -->	
	<%
		//request 내장 객체. 문자 인코딩 유형을 UTF-8로 작성
		request.setCharacterEncoding("utf-8");
		String userId = request.getParameter("id"); //admin
		String password = request.getParameter("passwd"); // java		
	%>
	
	<p>아이디 : <%out.print(userId); %></p>
	<p>비밀번호 : <%out.print(password); %></p>
	

</body>
</html>

 

결과