JSP(5. 내장 객체)

min seung moon·2021년 4월 1일
1

JSP

목록 보기
5/13

1. 내장 객체의 개요

01. 내장 객체(implicit object)

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

02. 내장 객체의 종류


03. 속성 처리 메소드의 종류

  • request, session, application, pageContext

2. request 내장 객체의 기능과 사용법

01. request 내장 객체

  • JSP 페이지에서 가장 많이 사용되는 기본 내장 객체
  • 웹 브라우저에서 서버의 JSP 페이지로 전달하는 정보를 저장
    • 폼 페이지로부터 입력된 데이터를 전달하는 요청 파라미터 값을 JSP 페이지로 가져 옴
  • JSP 컨테이너는 웹 브라우저에서 서버로 전달되는 정보를 처리하기 위해 javax,servlet.http.HttpServletRequest 객체 타입의 request 내장 객체를 사용하여 사용자의 요구 사항을 얻어 냄

02. 요청 파라미터 관련 메소드

  • 요청 파라미터는 사용자가 폼 페이지에 데이터를 입력한 후 서버에 전송할 때 전달되는 폼 페이지의 입력된 정보 형태를 말함
  • 요청 파라미터는 <name=value>형식으로 웹 브라우저에서 서버의 JSP 페이지로 전송

03. 요청 파라미터 관련 메소드의 종류


예제 01

  • request 내장 객체로 폼 페이지로부터 아이디와 비밀번호를 전송받아 출력하기

  • request01.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="request01_process.jsp" method="post">
		<p> 아이디 : <input type="text" name="id" value="" placeholder="아이디 입력" /></p>
		<p> 비밀번호 : <input type="password" name="password" value="" placeholder="비밀번호 입력"/></p>
		<p><input type="submit" value="전송"/>
	</form>
</body>
</html>
  • request01_process.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		request.setCharacterEncoding("UTF-8");
		String userId = request.getParameter("id");
		String userPw = request.getParameter("password");
	%>
	<p>아이디 : <%=userId %></p>
	<p>비밀번호 : <%=userPw %></p>
	
</body>
</html>

04. 요청 HTTP 헤더 관련 메소드

  • 웹 브라우저는 HTTP 헤더에 부가적인 벙보를 담아 서버로 전송

05. 요청 HTTP 헤더 관련 메소드의 종류


예제 02

  • request 내장 객체로 모든 HTTP 헤더 정보 값 출력하기
  • request02.jsp
<%@page import="java.util.Enumeration"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		Enumeration en = request.getHeaderNames();
		while(en.hasMoreElements()) {
			String headerName = (String) en.nextElement();
			String headerValue = request.getHeader(headerName);
		
	%>
	<%= headerName %> : <%=headerValue %><br>
	<%
		}
	%>
</body>
</html>

06. 웹 브라우저/서버 관련 메소드


예제 03

  • request 내장 객체로 모든 웹 브라우저 및 서버 정보 값 출력하기
  • request03.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<p>클라이언트 IP : <%=request.getRemoteAddr() %></p>
	<p>요청 정보 길이 : <%=request.getContentLength() %></p>
	<p>요청 정보 인코딩 : <%=request.getCharacterEncoding() %></p>
	<p>요청 정보 콘텐츠 유형 : <%=request.getContentType() %></p>
	<p>요청 정보 프로토콜 : <%=request.getProtocol() %></p>
	<p>요청 정보 전송 방식 : <%=request.getMethod() %></p>
	<p>요청 URI : <%=request.getRequestURI() %></p>
	<p>콘텍스트 경로 : <%=request.getContextPath() %></p>
	<p>서버 이름 : <%=request.getServerName() %></p>
	<p>서버 포트 : <%=request.getServerPort() %></p>
	<p>쿼리문 : <%=request.getQueryString() %></p>
</body>
</html>

3. response 내장 객체의 기능과 사용법

01. response 내장 객체

  • 사용자의 요청을 처리한 결과를 서버에서 웹 브라우저로 전달하는 정보를 저장하고 서버는 응답 헤더와 요청 처리 결과 데이터를 웹 브라우저로 보냄
  • JSP 컨테이너는 서버에서 웹 브라우저로 응답하는 정보를 처리하기 위해 javax.servlet.http.HttpServelteResponse 객체 타입의 response 내장 객체를 사용하여 사용자의 요청에 응답

02. 페이지 이동 관련 메소드

  • 페이지 이동 = 리다이렉션(redirection)
    • 사용자가 새로운 페이지를 요청할 때와 같이 페이지를 강제로 이동하는 것
  • 서버는 웹 브라우저에 다른 페이지로 강제 이동하도록 response 재장 객체의 리다이렉션 메소드를 제공
  • 페이지 이동 시에는 문자 인코딩을 알맞게 설정해야 함
  • forward와의 차이
    • 요청을해서 A라는 페이지로 이동해주세요, 하는데 요청자에게 block이 되서 정보를 제한적으로 이동(내가 갖고 있는 페이지에서만 이동이 가능)
    • redirect를 하게되면 내가 갖고 있지 않더라도 요청자에게 정보를 공개적으로 제공(내가 갖고 있지 않더라도 페이지 이동 가능)

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


예제 04.

  • responsse 내장 객체로 페이지 이동하기



  • response01.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="response01_process.jsp" method="post">
		<p> 아이디 : <input type="text" name="id" /></p>
		<p> 비밀번호 : <input type="text" name="password"/> </p>
		<p> <input type="submit" value="전송"></p>
		
	</form>
</body>
</html>
  • response_process.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		request.setCharacterEncoding("UTF-8");
		String userId = request.getParameter("id");
		String userPw = request.getParameter("password");
		
		if(userId.equals("관리자") && userPw.equals("1234")) {
			response.sendRedirect("response01_success.jsp");
		}else{
			response.sendRedirect("response01_failed.jsp");
		}
	%>
</body>
</html>
  • response01_success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	로그인 성공 했습니다
</body>
</html>
  • response01_failed.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<p>로그인을 실패하였습니다</p>
	<p><a href="./response01.jsp">로그인 가기</a></p>
</body>
</html>

04. 응답 HTTP 헤더 관련 메소드

  • 응답 HTTP 헤더 관련 메소드는 서버가 웹 브라우저에 응답하는 정보에 헤더를 추가하는 기능을 제공
  • 헤더 정보에는 주로 서버에 대한 정보가 저장되어 있음

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


예제 05.

  • response 내장 객체로 5초마다 JSP 페이지 갱신하기

06. 응답 콘텐츠 관련 메소드

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

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


예제 06.

  • response 내장 객체로 오류 응답 코드와 오류 메시지 보내기
  • response03.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		response.sendError(404,"요청 페이지를 찾을 수 없습니다");
	%>
</body>
</html>

4. out 내장 객체의 기능과 사용법

01. out 내장 객체

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

02. out 내장 객체 메소드의 종류


예제 07.

  • out 내장 객체로 오늘의 날짜 및 시각 출력하기
  • out01.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		out.println("오늘의 날짜 및 시각 "+"<br>");
		out.println(java.util.Calendar.getInstance().getTime());
	%>
</body>
</html>

예제 08.

  • out 내장 객체로 폼페이지에서 아이디와 비밀번호를 전송받아 출력하기

  • out02.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="out02_process.jsp" method="post">
		<p> 아이디 : <input type="text" name="id" /> </p>
		<p> 비밀번호 : <input type="password" name="password" /> </p>
		<p><input type="submit" value="전송"/></p>
	</form>
</body>
</html>
  • out02_process.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		request.setCharacterEncoding("UTF-8");
		String userId = request.getParameter("id");
		String userPw = request.getParameter("password");
	%>
	<p> 아이디 : <% out.println(userId); %></p>
	<p> 비밀번호 : <% out.println(userPw); %></p>
</body>
</html>

5. 웹 쇼핑몰 상품 상세 정보 표시하기


  • Webmarket/src/dao/ProductRepository.java
package dao;

import java.util.ArrayList;
import dto.Product;

public class ProductRepository {
	
	private ArrayList<Product> listOfProducts = new ArrayList<Product>();
	
	public ProductRepository() {
		Product phone = new Product("P1234", "iPhone 6s", 800000);
		phone.setDescription("4.7-inch, 1334X750 Renina HD display, 8-megapixel iSight Camera");
		phone.setCategory("Smart Phone");
		phone.setManufacturer("Apple");
		phone.setUnitInStock(1000);
		phone.setCondition("New");
		
		Product notebook = new Product("P1235", "LG PC 그램", 1500000);
		notebook.setDescription("13.3-inch, IPS LED display, 5rd Generation notebook. Inter Core processors");
		notebook.setCategory("Notebook");
		notebook.setManufacturer("LG");
		notebook.setUnitInStock(1000);
		notebook.setCondition("Refurbished");
		
		Product tablet = new Product("P1236", "Galaxy Tab S", 900000);
		tablet.setDescription("212.8*125.6*6.6mm, Super AMOLEED display, Octa-Core processor");
		tablet.setCategory("Tablet");
		tablet.setManufacturer("Samsum");
		tablet.setUnitInStock(1000);
		tablet.setCondition("Old");
		
		listOfProducts.add(phone);
		listOfProducts.add(notebook);
		listOfProducts.add(tablet);
	}
	
	public ArrayList<Product> getAllProducts() {
		return listOfProducts;
	}
	
	public Product getProductById(String productId) {
		Product productById = null;
		
		for (int i = 0; i < listOfProducts.size(); i++) {
			Product product = listOfProducts.get(i);
			if(product != null && product.getProductId() != null && product.getProductId().equals(productId)){
				productById = product;
				break;
			}
		}
		return productById;
	}
}
  • Webmarket/WebContent/header.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>header</title>
<style>
* {
	margin: 0;
	padding: 0;
	box-sizing: border-box;
}

a {
	color: #000;
	text-decoration: none;
}

header {
	background-color: #000;
	width: 100%;
	padding: 10px 20px;
}

header a {
	color: #fff;
	font-weight: 700;
}

.container {
	width: 90%;
	margin: 0 auto;
}
.btn {
	padding : 10px 5px;
	background-color : #696b6a;
	color : #fff;
	border-radius : 7px;
}
.btn:hover {
	background-color : #404040;
}
.btn.btn-secondary {
	background-color : #2a9abd;
}
.btn.btn-secondary:hover {
	background-color : #0f496b;
}

.main {
	width: 100%
}

.main .banner {
	width: 100%;
	height: 300px;
	background-color: #d1d1d1;
	line-height: 300px;
}

.main .banner h1 {
	font-size: 6vw;
	font-weight: 100;
}
.main .content {
	width: 100%
}
</style>
</head>
<body>
	<header>
		<div class="container">
			<a href="index.jsp">Home</a>
		</div>
	</header>
</body>
</html>
  • Webmarket/WebContent/products.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="java.util.ArrayList"%>
<%@ page import="dto.Product"%>
<jsp:useBean id="productDAO" class="dao.ProductRepository"
	scope="session" />
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>상품 목록</title>
<style>
.main {
	width: 100%
}

.main .banner {
	width: 100%;
	height: 300px;
	background-color: #d1d1d1;
	line-height: 300px;
}

.main .banner h1 {
	font-size: 6vw;
	font-weight: 100;
}

.main .content {
	width: 100%
}

.main .content .row {
	display: flex;
	justify-content: space-around;
	align-items: center;
}

.main .content .row .column {
	width: 300px;
	display: flex;
	flex-direction: column;
	justify-content: center;
	margin: 15px 0;
}

.main .content .row .column h3, .main .content .row .column p {
	text-align: center;
	padding: 10px;
}

.main .content .row .column h3 {
	font-size: 1.7rem;
	font-weight: 400;
}
</style>
<%!String greenting = "상품목록";%>
</head>
<body>
	<jsp:include page="header.jsp" />

	<div class="main">

		<div class="banner">
			<div class="container">
				<h1><%=greenting%></h1>
			</div>
		</div>

		<div class="content">
			<div class="container">
				<div class="row">
					<%
						ArrayList<Product> listOfProduct = productDAO.getAllProducts();

						for (int i = 0; i < listOfProduct.size(); i++) {
							Product product = listOfProduct.get(i);
					%>
					<div class="column">
						<h3><%=product.getPname()%></h3>
						<p><%=product.getDescription()%></p>
						<p><%=product.getUnitPrice()%>원
						</p>
						<p>
							<a href="./product.jsp?id=<%=product.getProductId()%>"
								class="btn" role="button">상세 정보&raquo;</a>
					</div>
					<%
						}
					%>
				</div>
				<hr>
			</div>
		</div>


	</div>

	<jsp:include page="footer.jsp" />
</body>
</html>
  • Webmarket/WebContent/product.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="dto.Product"%>
<jsp:useBean id="productDAO" class="dao.ProductRepository"
	scope="session" />
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>상품 상세 정보</title>
<style>
	.content .row {
		padding : 30px 0;
	}
	.content h3, .content p, .content h4 {
		margin : 25px 0;
	}
	.content h3 {
		margin-bottom : 5px;
	}
	.content .description {
		margin-top : 5px;
	}
	.content .badge {
		background-color : #f00;
		color : #fff;
		border-radius : 5px;
	}
</style>
</head>
<body>
	<jsp:include page="header.jsp" />
	<div class="main">
		<div class="banner">
			<div class="container">
				<h1>상품 정보</h1>
			</div>
		</div>

		<%
			String id = request.getParameter("id");
			Product product = productDAO.getProductById(id);
		%>
		<div class="content">
			<div class="container">
				<div class="row">
					<h3><%=product.getPname()%></h3>
					<p class="description"><%=product.getDescription()%></p>
					<p>
						<b>상품 코드 : </b><span class="badge"><%=product.getProductId()%></span>
					<p>
						<b>제조사</b> :
						<%=product.getManufacturer()%></p>
					<p>
						<b>분류</b> :
						<%=product.getCategory()%></p>
					<p>
						<b>재고 수</b> :
						<%=product.getUnitInStock()%>
					</p>
					<h4><%=product.getUnitPrice()%>원</h4>
					<p>
						<a href="#" class="btn btn-secondary">상품 주문 &raquo;</a> 
						<a href="./products.jsp" class="btn">상품 목록 &raquo;</a>
					</p>
				</div>
				<hr>
			</div>
		</div>
	</div>
	<jsp:include page="footer.jsp" />
</body>
</html>
  • Webmarket/WebContent/index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@page import="java.util.Date"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome</title>
<style>
.main {
	width: 100%
}

.main .banner {
	width: 100%;
	height: 300px;
	background-color: #d1d1d1;
	text-align: center;
	line-height: 300px;
}

.main .banner h1 {
	font-size: 5vw;
	font-weight: 400;
}

.main .content {
	width: 100%;
	margin: 0 auto;
	padding: 10px;
	text-align: center;
}

.main .content h3 {
	margin: 0 auto;
	padding: 20px 0;
	font-weight: 100;
}

.main .content p {
	margin-bottom: 30px;
}
</style>
<%!String greenting = "웹 쇼핑몰에 오신 것을 환영합니다";
	String tagLine = "Welcome to Web Market";%>
</head>
<body>
	<jsp:include page="header.jsp" />

	<div class="main">

		<div class="banner">
			<div class="container">
				<h1><%=greenting%></h1>
			</div>
		</div>

		<div class="content">
			<div class="container">
				<h3><%=tagLine%></h3>
				<p>
					<%
						response.setIntHeader("Refresh", 5);
						Date day = new Date();
						String am_pm;
						int hour = day.getHours();
						int minute = day.getMinutes();
						int second = day.getSeconds();
						if (hour / 12 == 0)
							am_pm = "AM";
						else {
							am_pm = "PM";
							hour = hour - 12;
						}
						String CT = hour + ":" + minute + ":" + second + " " + am_pm;
						out.println("현재 접속 시각 : " + CT + "\n");
					%>
				
				<p>
				<hr>
			</div>
		</div>
	</div>

	<jsp:include page="footer.jsp" />
</body>
</html>
profile
아직까지는 코린이!

0개의 댓글