티스토리 뷰

JSP

서블릿 컨텍스트

yoooon1212 2024. 7. 1. 16:14

서블릿 컨텍스트 (ServletContext)

웹 애플리케이션의 실행 환경을 나타내는 객체로, 애플리케이션 전반에 걸쳐 공유되는 정보를 제공하고 애플리케이션 자원에 접근할 수 있게 해줍니다.

웹 애플리케이션이 초기화될 때 서버에 의해 생성되며, 애플리케이션이 종료될 때까지 유지됩니다.

 

ServletContext의 주요 역할

  • 초기화 파라미터 읽기: web.xml에 정의된 초기화 파라미터를 읽을 수 있습니다.
  • 로그 작성: 애플리케이션 수준의 로그를 작성할 수 있습니다.
  • 자원 접근: 웹 애플리케이션의 자원 (파일 등)에 접근할 수 있습니다.
  • 다른 서블릿과의 통신: 다른 서블릿이나 JSP와 정보를 공유할 수 있습니다.

 

코드 예시

HTML File 생성

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
body {
	font-family: Arial, sans-serif;
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100vh;
	margin: 0;
	background-color: #f0f0f0;
}

.container {
	background-color: white;
	padding: 20px;
	border-radius: 10px;
	box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
	width: 300px;
	text-align: center;
}

.title {
	font-size: 24px;
	font-weight: bold;
	margin-bottom: 20px;
}

.task-list {
	display: flex;
	flex-direction: column;
	gap: 10px;
}

.task {
	background-color: #e0e0e0;
	padding: 10px;
	border-radius: 5px;
}
</style>
</head>
<body>
	<div class="container">
		<div class="title">할 일 목록</div>
		<div class="task-list">
			<div class="task">쇼핑하기</div>
			<div class="task">책 읽기</div>
			<div class="task">운동하기</div>
			<div class="task">코딩 공부하기</div>
		</div>
	</div>
</body>
</html>

 

 

서블릿 컨텍스트를 활용하여 서블릿 클래스 작성

 

 

getResourceAsStream 메서드

ServletContext의 메서드로, 지정된 경로에 있는 자원을 InputStream으로 반환합니다.

이를 통해 웹 애플리케이션 내의 파일을 읽을 수 있습니다.

// 현재 서블릿의 ServletContext 객체를 가져옵니다.
ServletContext context = getServletContext(); 

// 지정된 경로에 있는 자원을 읽어들입니다. 
// 반환된 InputStream을 통해 파일의 내용을 읽을 수 있습니다.
InputStream inputStream = context.getResourceAsStream(htmlFilePath);

'JSP' 카테고리의 다른 글

server.xml, context.xml, web.xml  (0) 2024.07.02
서블릿과 DB 연동  (0) 2024.07.01
GET, POST 요청 방식  (0) 2024.07.01
서블릿 작성, 배포, web.xml 설정  (0) 2024.07.01
서블릿 및 서블릿 life cycle  (0) 2024.07.01
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함