Java Category/JSP

[JSP] 내장 객체

ReBugs 2023. 11. 24.

내장 객체란

  • JSP 페이지에서 사용할 수 있도록 JSP 컨테이너에 미리 정의된 객체
  • JSP 페이지가 서블릿 프로그램으로 번역될 때 JSP 컨테이너가 자동으로 내장 객체를 멤버 변수, 메소드 매개변수 등의 각종 참조 변수(객체)로 포함
  • JSP 페이지에 별도의 import문 없이 자유롭게 사용 가능
  • 스크립틀릿 태그나 표현문 태그에 선언을 하거나 객체를 생성하지 않고도 직접 호출하여 사용 가능

 

내장 객체의 종류

 

내장 객체의 속성관리

  • JSP는 HTTP 프로토콜의 사용하는 웹 환경에서 구동되는 프로그램
  • HTTP는 비연결형으로 사용자가 서버에 특정 페이지를 요청하고 요청결과를 응답받으면 서버와의 연결이 끊기는 형태
    예를 들어 게시판에 글을 작성하는 페이지에서 작성한 내용은 다른 jsp에서 처리해야 하고 서버는 방금 글을 작성한 사람이 누구인지 모를 수 있음
  • JSP 에서  page, request, session, application 내장객체를 통해 서로 다른 페이지에서 처리된 값을 저장하고 공유하기 위한 방법을 제공
  • 이는 컨테이너 기반 프로그램의 특징 중 하나로 실제 프로그램 구현 시 매우 중요한 기법

https://javappo.tistory.com/215

  1. application은 모든 사용자가 공유하는 데이터를 저장할 수 있으며 톰캣이 종료될 때 까지 데이터를 유지할 수 있다(맨 위의 user1, user2 해당). 
  2. session의 경우 사용자마다 분리된 저장 영역이 있으며 Page1, Page2, Page3 모두에서 공유되는 정보를 관리할 수 있다. 물론 이 데이터는 각자 공유 영역에서 관리되며 사용자 간에는 공유되지 않는다. 
  3. 페이지 흐름이 Page1, Page2, Page3순으로 진행된다고 할 때, 한 페이지에서 다른 페이지로 데이터를 전달하려면 request 내장객체를 이용해야 한다.(맨 아래의 user1에 해당한다). page 마다 생성됨.

  • request, session, application 은 각각 생성 시점과 소멸시점이 다르며 이를 잘 이해하고 적절한 내장객체를 이용해야 한다.
  • 각각의 내장객체는 모두 getAttribute(), setAttribute() 메서드를 통해 속성을 저장하거나 가져올 수 있다.

reference : https://javappo.tistory.com/215

 

속성 처리 메소드의 종류

request, session, application

 

 

request

  • JSP 페이지에서 가장 많이 사용되는 기본 내장 객체
  • 웹 브라우저에서 서버의 JSP 페이지로 전달하는 정보를 저장
  • 폼 페이지로부터 입력된 데이터를 전달하는 요청 파라미터 값을 JSP 페이지로 가져 옴

 

예제

더보기

Requestjoin.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<center>
		<h2>회원 가입</h2>
		<form action="RequestJoinProc.jsp">
			<table width="500" border="1">
				<tr height="50">
					<td width="150" align="center">아이디 </td>
					<td width="350" align="center">
						<input type="text" name="id" size="40" placeholder="id를 넣으세요">						
					</td>
				</tr>
		
				<tr height="50">
					<td width="150" align="center">패스워드</td>
					<td width="350" align="center">
						<input type="password" name="pass1" size="40"
						placeholder="비밀번호는 숫자와 영어만 넣어주세요">						
					</td>
				</tr>
				
				<tr height="50">
					<td width="150" align="center">패스워드 확인</td>
					<td width="350" align="center">
						<input type="password" name="pass2" size="40">						
					</td>
				</tr>
				
				<tr height="50">
					<td width="150" align="center">이메일</td>
					<td width="350" align="center">
						<input type="email" name="email" size="40">						
					</td>
				</tr>
				
				<tr height="50">
					<td width="150" align="center">전화 번호 </td>
					<td width="350" align="center">
						<input type="tel" name="tel" size="40">				
					</td>
				</tr>
				
				<tr height="50">
					<td width="150" align="center">당신의 관심 분야</td>
					<td width="350" align="center">
						<input type="checkbox" name="hobby" value="캠핑">캠핑&nbsp;
						<input type="checkbox" name="hobby" value="등산">등산&nbsp;
						<input type="checkbox" name="hobby" value="독서">독서&nbsp;
						<input type="checkbox" name="hobby" value="음악">음악&nbsp;				
					</td>
				</tr>
				
			   <tr height="50">
					<td width="150" align="center">당신의 직업은</td>
					<td width="350" align="center">
						<select name="job">
						<option value="교사">교사</option>
						<option value="의사">의사</option>
						<option value="변호사">변호사</option>
						<option value="기술사">기술사</option>
						</select>				
					</td>
				</tr>
				
				<tr height="50">
					<td width="150" align="center">당신의 연령은</td>
					<td width="350" align="center">
						<input type="radio" name="age" value="10">10대&nbsp;
						<input type="radio" name="age" value="20">20대&nbsp;
						<input type="radio" name="age" value="30">30대&nbsp;
						<input type="radio" name="age" value="40">40대&nbsp;			
					</td>
				</tr>
				
				<tr height="50">
					<td width="150" align="center">하고 싶은말</td>
					<td width="350" align="center">
							<textarea rows="5" cols="40" name="info"></textarea>	
					</td>
				</tr>
					
				<tr height="50">
					<td width="150" colspan="2">
						<input type="submit" value="회원 가입">	
						<input type="reset" value="취소">			
					</td>
				</tr>	
			</table>
		</form>	
	</center>
</body>
</html>

 

RequestjoinProc.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>	
<center>
<h2>회원 정보 보기</h2>

<% 
	//post방식으로 데이터가 넘어올때 한글이 깨질수 있기에 
    request.setCharacterEncoding("UTF-8");
	//각종 사용자로 부터 넘어온 데이터를 저장해줌
	String id    = request.getParameter("id");
	String pass1 = request.getParameter("pass1");
	String pass2 = request.getParameter("pass2");
	String email = request.getParameter("email");
	String  tel  = request.getParameter("tel");
	
	//[]열 타입으로 리턴 
	String [] hobby = request.getParameterValues("hobby");
	
	String job = request.getParameter("job");
	String age = request.getParameter("age");
	String info = request.getParameter("info");

	if(!pass1.equals(pass2)){
%>
	<script type="text/javascript">
		alert("비밀 번호가 틀립니다");
		history.go(-1);
	</script>	
<% 
	}
%>
	
<table width="400" border="1">
			<form action="RequestJoinProc.jsp">
			<table width="500" border="1">
				<tr height="50">
					<td width="150" align="center">아이디 </td>
					<td width="350" align="center"><%= id%>					
					</td>
				</tr>
				
				
				<tr height="50">
					<td width="150" align="center">이메일</td>
					<td width="350" align="center"><%= email%>						
					</td>
				</tr>
				
				<tr height="50">
					<td width="150" align="center">전화 번호 </td>
					<td width="350" align="center"><%= tel%>				
					</td>
				</tr>
				
				<tr height="50">
					<td width="150" align="center">당신의 관심분야</td>			
					<td width="350" align="center">
					<% 
					for(int i = 0;i<hobby.length;i++){
						out.write(hobby[i] +" ");
					}
					%>			
					</td>
				</tr>
				
				<tr height="50">
					<td width="150" align="center">직업은 </td>
					<td width="350" align="center"><%= job%>				
					</td>
				</tr>
				
				<tr height="50">
					<td width="150" align="center">전연령은</td>
					<td width="350" align="center"><%= age%>				
					</td>
				</tr>
				
				<tr height="50">
					<td width="150" align="center">하고 싶은말</td>
					<td width="350" align="center"><%= info%>				
					</td>
				</tr>

</table>
	
	
</center>
	
	
</body>
</html>

 

 

 

 

response

  • 페이지 이동 = 리다이렉션(redirection)
  • 사용자가 새로운 페이지를 요청할 때와 같이 페이지를 강제로 이동하는 것
  • 서버는 웹 브라우저에 다른 페이지로 강제 이동하도록 response 재장 객체의 리다이렉션 메소드를 제공
  • 페이지 이동 시에는 문자 인코딩을 알맞게 설정해야 함
response.sendRedirect("ResponseMain.jsp"); //해당 JSP 페이지로 이동
response.sendRedirect("ResponseMain.jsp?id="+id); //해당 JSP로 id라는 파라미터를 get방식으로 전송

 

응답 형식 지정 메소드

  • 컨텐츠 타입이나 문자셋에 대한 정보를 지정할 때 사용하는 메소드의 종류는 다음 표를 참조

 

응답 헤더 메소드

  • 헤더 정보나 쿠키 등에 대한 정보를 지정할 때 사용하는 메소드의 종류는 다음 표를 참조

 

페이지 이동 메소드

  • 웹 브라우저에서 지정한 특정 페이지로 이동할 때 사용하는 메소드의 종류는 다음 표를 참조

 

예제

더보기

ResponseSendredirect.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>

<center>
	<h2>로그인 페이지 </h2>
		<form action= "ResponseLoginProc.jsp" method="post">
		<table width="400" border="1">
			<tr height = "60">
				<td align="center" width ="150">아이디</td>
				<td align="left" width= "250">
					<input type="text" name="id">
				</td>
			</tr>
			
			<tr height ="60">
				<td align = "center" width="150">패스워드</td>
				<td align = "left" width="250">
					<input type ="password" name="pass">
				</td>
			</tr>
			
			<tr height ="60">
				<td colspan = "2" align = "center">
					<input type ="submit" value="전송">
				</td>
			</tr>
		</table>
		</form>
	</center>
</body>
</html>

 

ResponseLoginProc.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<h2>로그인 처리 페이지</h2>

<% 
	 request.setCharacterEncoding("EUC-KR");
	
	//임의적으로 id 와 pass를 설정 
	String dbid = "aaaa";
	String dbpass= "1234";
	
	//사용자로부터 넘어온 데이터를 입력받아줌 
	String id = request.getParameter("id");
	String pass = request.getParameter("pass");
	
	if(dbid.equals(id) && dbpass.equals(pass)){
		//아이디와 패스워드가 일치하니깐 메인 페이지를 보여주어야 합니다.
		response.sendRedirect("ResponseMain.jsp?id="+id);
	}else{
%>
	<script>
		alert("아이디와 패스워드가 일치 하지 않습니다");
		history.go(-1);
	</script>		
<% 		
	}
%>

</body>
</html>

 

ResponseMain.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
	<% 
		request.setCharacterEncoding("EUC-KR");
	%>
	
	<h2><%= request.getParameter("id")%> 님 반갑습니다</h2>
</body>
</html>

 

 

 

 

out

  • 웹 브라우저에 데이터를 전송하는 출력 스트림 객체
  • JSP 컨테이너는 JSP 페이지에 사용되는 모든 표현문 태그와 HTML, 일반텍스트 등을 out 내장 객체를 통해 웹 브라우저에 그대로 전달
  • 스크립틀릿 태그에 사용하여 단순히 값을 출려가는 표현문 태그(<%= ...%>)와 같은 결과를 얻을 수 있음

 

예제

댓글