[Spring] CH07 서블릿 고급 (책)

jaegeunsong97·2023년 2월 18일
0

[Fast Campus] Spring

목록 보기
8/44
post-thumbnail

📕 JSP 문법 배우기

https://github.com/codingspecialist/web2.git

web/user.jsp

<%@ page import="java.io.PrintWriter" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport"
		content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>Document</title>
</head>
<body>
	<h1>User 페이지</h1>
	<hr/>
	<%!
		String getUsername(){
			return "ssar";
		}
	%>
	<%
		PrintWriter pw = response.getWriter();
		pw.println(getUsername());
	%>
	<h3><%=getUsername()%></h3>
</body>
</html>

📕 JSP -> Servlet 변환 원리

개발자는 JSP에서 작업을 하고, 톰켓이 JSP를 Servlet파일로 변환시켜준다.

web/index.jsp

<%@ page import="java.util.Random" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
	<title>Index</title>
</head>
<body>
<h1>Index Page</h1>
<hr/>
<%
	Random r = new Random();
	int num = r.nextInt(5)+1;
%>
<h2>당신의 번호는 : <%=num%></h2>
</body>
</html>

src/MyServlet.java

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

@WebServlet("*.do")
public class MyServlet extends HttpServlet {
	@Override
		protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			resp.setContentType("text/html; charset=utf-8");
			PrintWriter out = resp.getWriter();
			String html1 = "<html>\n" +
                  "<head>\n" +
                  " <title>Index</title>\n" +
                  "</head>\n" +
                  "<body>\n" +
                  "<h1>Index Page</h1>\n" +
                  "<hr/>\n";
			out.println(html1);
			// 자바 영역 파싱
			Random r = new Random();
			int num = r.nextInt(5) + 1;
			String html2 = "<h2>당신의 번호는 : ";
			out.println(html2);
            // 자바 영역 파싱
            out.println(num);
            String html3 = "</h2>\n" +
                  "</body>\n" +
                  "</html>";
			out.println(html3);
		}
}

📕 Servlet으로 HTML을 만드는 것은 힘들다

web/airbnb.jsp
https://github.com/codingspecialist/web2/blob/main/web/airbnb.jsp

📕 서블릿 스코프

서블릿에서는 필요시 임의의 데이터를 저장하고 나중에 저장된 데이터를 사용할 수 있는 4가지 저장소를 제공한다.

📜 Page 스코프

  • 한 번의 클라이언트 요청으로 하나의 JSP 페이지가 응답한다.
  • 하나의 JSP 페이지 내에서만 데이터를 저장 및 공유 한다.
pageContext.setAttribute("키", "값");

📜 Request 스코프

  • HttpServletRequest API 사용
  • 요청 ~ 응답까지의 Life Cycle을 가진다. (Response 시 해당 스코프는 삭제 된다.)
request.setAttribute("키", "값");

📜 Session 스코프

  • HttpSession API 사용
  • 브라우저의 Life Cycle을 가짐
  • 클라이언트의 브라우저가 종료되거나..
  • 세션에 설정된 시간동안 클라이언트가
session.setAttribute("키", "값");

📜 Application

  • 해당 어플리케이션이 종료 되기 전까지 저장한다.
  • SerlvetContext API 사용
  • 웹 어플리케이션에서의 context의 Life Cycle을 가짐
application.setAttribute("키", "값");

📕 EL 표현식

EL 표현식을 사용하면 서블릿 스코프에 저장된 모든 값을 찾을 수 있다.

${pageScope.pageData}
${requestScope.requestData}
${sessionScope.sessionData}
${applicationScope.applicationData}

scope를 앞에 붙이지 않고 접근이 가능하다.
이렇게 접근하게 되면 pageScope로 가서 찾고, 없으면 requestScope로 가서 찾고, 없으면 sessionScope로 가서 찾고, 없으면 applicationScope로 가서 찾는다.

${requestData}

web/board.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    pageContext.setAttribute("pageData", "1111"); //page scope
    request.setAttribute("requestData", "2222"); // request scope
    session.setAttribute("sessionData", "3333"); // session scope
    application.setAttribute("applicationData", "4444"); // application scope
%>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
		content="width=device-width, user-scalable=no, initial-scale=1.0,
    maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Servlet Scope</h1>
<hr/>
${pageScope.pageData} <br/>
${requestScope.requestData} <br/>
${sessionScope.sessionData} <br/>
${applicationScope.applicationData} <br/>
</body>
</html>

📕 서블릿 스코프가 필요한 이유

📜 request

클라이언트는 서버쪽으로 요청을 하고, 응답이 될 때까지 변수를 저장할 필요가 있다. 이런 데이터는
request 에 저장한다.

📜 session

클라이언트는 서버쪽으로 요청을 하고, 응답을 받은 뒤 다시 재요청을 했을 때, 서버는 stateless 무상태
서버이기 때문에 클라이언트를 기억하지 못한다.
클라이언트를 기억하기 위한 데이터 저장 공간이 필요하다. 이런 데이터는 session에 저장한다.

profile
블로그 이전 : https://medium.com/@jaegeunsong97

0개의 댓글