[스프링부트] 2. Servlet

문정준's avatar
Mar 12, 2025
[스프링부트] 2. Servlet

1. New Project

  • Jakarta EE 사용
  • 이름, 위치, Template, Application Server, Build System 설정
    • Template : Web application
    • Application server : Tomcat 11.0.5 ( 자신이 설치한 Tomcat 버전 )
notion image
 

Server가 없을 때

  • New 클릭
  • Tomcat Server 클릭
notion image
 
  • 폴더 모양 아이콘 클릭
  • C:\Program Files\Apache Software Foundation\Tomcat 11.0 선택
  • OK를 눌러 지정
notion image
 
  • 폴더 구조 필히 확인
    • 생성 시 필수 파일 다운로드 필요, 다운로드 완료 전까지는 서버를 작동시키지 말 것
notion image
 

2. Context Path

  • Context Path : 파일의 위치를 파악할 수 있는 경로, 어플리케이션을 구분하기 위함
  • 여러 개의 프로젝트 중 실행할 파일을 고를 수 있게 하는 경로
  • CP를 생략(/)하게 되면, IP주소:포트번호만 입력해도 앱을 실행시킬 수 있음
    • 네이버, 다음 등 포털사이트 등에서 도메인만 입력해도 바로 html을 실행하는 것과 같음
notion image
 

Context Path 설정 방법

  • IntelliJ 상단의 Tomcat 11.0.5 클릭 → Edit Configurations 클릭
  • Deployment 클릭
    • Application context를 ‘/’로 변경
notion image
 
  • 이후 WAP를 실행하면 뒤의 URI가 사라진 것을 확인 가능
notion image
 

3. Home Repository of WAP

  • webapp, resources 두 곳에 각각 hello.css, style.css 파일 작성
notion image
 
  • resources의 style.css에 링크 → 반영 안됨
notion image
 
  • 파일 수정 후 즉시 반영이 안됨
    • 서버 재 시작 필요 ( Redeploy )
notion image
 
  • Redeploy 이후 반영된 것을 확인 가능
notion image
 
✏️

WAP의 기본 폴더는 webapp!

 

4. 보안 폴더

  • WEB-INF 내부에 a.txt 파일 생성 후 홈페이지에서 실행을 해도 접근할 수 없음
  • WEB_INF는 보안 폴더 : 외부에서 접근할 수 없음
    • 내부에서는 접근 가능
notion image
notion image
 
✏️

WEB_INF는 보안 폴더

  • 외부에서 Direct Access는 불가능
✏️

Index.html에서 WEB_INF를 참조해도 파일을 찾을 수 없는 이유

  • 내부 폴더에서 참조하면 찾을 수 있을 듯 하지만, 결국 파일을 요청하는 주체는 클라이언트기 때문에, index.html에서 파일을 참조해도 클라이언트 측 요청으로 처리하기 때문에 외부 접근으로 인식, 차단됨.
 
 
notion image
notion image
 
package org.example.demo; import java.io.*; import jakarta.servlet.ServletException; import jakarta.servlet.http.*; import jakarta.servlet.annotation.*; // Client와 1:1 소통이 가능한 클래스 // Allocation : JVM이 보는 힌트 (Reflection) -> @WebServlet("/hello.do") public class HelloServlet extends HttpServlet { @Override // req : 요청 버퍼에 담긴 모든 텍스트를 객체화한 것 // resp : 응답 버퍼에 접근할 수 있는 객체 ( BufferedWriter 내장 ) protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String html = """ <html> <head> <title>Servlet</title> </head> <body> """; for(int i=0;i<10;i++){ html = html + """ <h1>$i</h1> """.replace("$i", i+""); } html = html+""" </body> </html> """; PrintWriter out = resp.getWriter(); out.println(html); } }
 
notion image
 
 
Share article

sxias