Servlet/JSP 내장 객체와 범위(scope)
✔️ Servlet/JSP에는 기본적으로 내장되어있는 4가지 객체가 존재함
✔️ 4종류의 객체는 각각 영향을 미칠 수 있는 범위가 다르다
1. page : 현재 페이지
-> 현재 Servlet 또는 JSP에서만 사용 가능 (1페이지)
2. request : 요청받은 페이지(Servlet/JSP)와
요청을 위임받은 페이지(Servlet/JSP)에서 사용 가능
3. session : 현재 사이트에 접속한 브라우저당 1개씩 생성.
브라우저가 종료되거나, session이 만료될 때 까지 유지
(세션에 로그인 정보를 기록해둠
-> 브라우저가 종료되거나 로그아웃 되기 전까지 계속 로그인 상태 유지됨)
4. application : 하나의 웹 애플리케이션 당 1개만 생성되는 객체
-> 서버 시작 시 생성되며 종료 시 까지 유지
-> 누구든지 사용 가능
💡 내장 객체의 우선 순위
✔️ setAttribute("key", value)로 내장 객체가 값을 세팅할 때 key 값이 중복되는 경우
${key}로 작성하는 경우 범위가 작은 내장 객체가 높은 우선 순위를 가진다
page > request > session > application
1) index.html
<ul>
<li>
<a href="scope">2. Servlet/JSP 내장 객체와 범위(scope)</a>
</li>
</ul>
2) servlet
@WebServlet("/scope")
public class ScopeServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
RequestDispatcher dispatcher =
req.getRequestDispatcher("/WEB-INF/views/el/scope.jsp");
req.setAttribute("message", "request scope에 저장된 메시지 입니다");
HttpSession session = req.getSession();
session.setAttribute("sessionValue", "999");
ServletContext application = req.getServletContext();
application.setAttribute("appValue", "애플리케이션 범위 값");
req.setAttribute("str", "request scope");
session.setAttribute("str", "session scope");
application.setAttribute("str", "application scope");
dispatcher.forward(req, resp);
}
}
3) JSP
💡 상단에 작성!!
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
----------------------------- 생략 -----------------------------
<ul>
<li>
<% pageContext.setAttribute("pageMsg", "페이지 범위 입니다");
pageContext.setAttribute("str", "page scope"); %>
page scope pageMsg : ${pageMsg}
</li>
<li>request scope message : ${message}</li>
<li>session scope sessionValue : ${sessionValue}</li>
<li>application scope appValue : ${appValue}</li>
</ul>
<<hr>
<h1>우선 순위 확인 : ${str}</h1>
<h3>page의 str 값 : ${pageScope.str}</h3>
<h3>request의 str 값 : ${requestScope.str}</h3>
<h3>session의 str 값 : ${sessionScope.str}</h3>
<h3>application의 str 값 : ${applicationScope.str}</h3>