본문 바로가기

JSP/2단원 - 서블릿 기본 개념과 활용

서블릿과 서블릿 컨텍스트란?

💡 학습 목표

1. 정적 자원이라는 개념을 이해하자.
2. 서블릿 컨테스트는 머야?

 

 

class_sevlet_01 프로젝트 webapp/todolist.html 생성

flexbox 사용

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <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>

 

 

서블릿 컨택스트란는 녀석을 활용해서 서블릿 클래스를 작성해보자.

package com.tenco.controller;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;


@WebServlet("/todolist")
public class TodoListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

    public TodoListServlet() {
        super();

    }
    
    // GET 방식 
    // http://localhost:8080/class_sevlet_01/todolist
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 다시 HTML 형식을 만들어서 클라이언트에게 내려주는 것은 
		// 서블릿에서 너무 불편하다. 
		// 서블릿 컨텍스트라는 객체를 활용해서 코드를 만들어 보자. 
		
		response.setContentType("text/html;charset=UTF-8");
		
		// HTML 파일 읽기 
		String htmlFilePath = "/todoListPage.html";
		InputStream inputStream = getServletContext().getResourceAsStream(htmlFilePath);
		if (inputStream == null) {
			response.getWriter().write("<html><body>해당 파일을 찾을 수 없음 404</body></html>");
		}
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
		
		StringBuffer htmlContent = new StringBuffer();
		String line;
		while( (line = reader.readLine()) != null  ) {
			htmlContent.append(line);
		}
		reader.close();
		response.getWriter().write(htmlContent.toString());
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}

}

 

 

1. 서블릿 컨텍스트 (ServletContext)

ServletContext는 웹 애플리케이션의 실행 환경을 나타내는 객체로, 애플리케이션 전반에 걸쳐 공유되는 정보를 제공하고 애플리케이션 자원에 접근할 수 있게 해줍니다. ServletContext는 웹 애플리케이션이 초기화될 때 서버에 의해 생성되며, 애플리케이션이 종료될 때까지 유지됩니다.

ServletContext의 주요 역할:

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

2. getResourceAsStream 메서드

getResourceAsStream 메서드는 ServletContext의 메서드로, 지정된 경로에 있는 자원을 InputStream으로 반환합니다. 이를 통해 웹 애플리케이션 내의 파일을 읽을 수 있습니다.

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

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