Backend/Servlet

Session & Servlet api

AIHYEONJI 2025. 6. 5. 12:01

** Session

  • 서버와의 관계를 유지하기 위한 수단
  • 서버상에 객체형태로 존재
  • 서버당 하나의 세션 객체를 가질 수 있음  ↔   브라우저 별 서로 다른 세션 사용( = 서로 다른 클라이언트로 인식함 )
  • 브라우저 창을 종료하면 삭제 (MaxAge에 따라 간혹가다 유지되는 경우도 있지만, 거의 없음)
  • 서버에서만 접근이 가능하여 보안이 좋고, 저장할 수 있는 데이터에 한계가 없음 단, 메모리의 한계가 있음
  • 클라이언트의 요청이 발생하면 자동생성되어 고유한 ID값을 클라이언트에 넘겨주며 이것을 쿠키에 저장
더보기

[ 브라우저 1]      →       [ 세션객체 ]   : 브라우저가 다르면 세션객체가 따로만들어짐

[ 브라우저 2]     →           ↑

 

※ 로그인 유저를 세션 타임 내 요청을 안하면 로그인 불가함.

※ 세션과 토큰과의 차이점?

서버를 만들면 동기화를 하는데, 요즘은 서버를 여러개 쓰기때문에 수 많은 유저가 접속을 하게 되면 서버 과부화에 빠지기 쉽다.  그래서 한 서버를 이용하면서 여러 창을 이동하다보면, 로그인 메모리가 날라가 자동 로그아웃된다. 이러한 세션의 단점 때문에 토큰을 사용한다. → 유저가 많이 없으면 세션 사용해도 충분..^^

 

<%--
    Session
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>session</title>
</head>
<body>
<form method="post" action="7_session_ok.jsp">
    <p>아이디: <input type="text" name="userid"></p>
    <p>비밀번호: <input type="password" name="userpw"></p>
    <p><button type="submit">로그인</button></p>
</form>
</body>
</html>

 

<%--
    7_session_ok.jsp
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String userid = request.getParameter("userid");
    String userpw = request.getParameter("userpw");

    if(userid.equals("admin") && userpw.equals("1234")){
        // session 보안용
        session.setAttribute("userid",userid);
        response.sendRedirect("7_session_success.jsp");
    }else{
        response.sendRedirect("7_session_fail.jsp");
    }

%>
<html>
<head>
    <title>session</title>
</head>
<body>

</body>
</html>

 

<%--
    7_session_success.jsp
    세션의 유무 판단
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    if(session.getAttribute("userid")==null){
        response.sendRedirect("7_session.jsp");
    }
    // userid는 세션안의 객체를 가져오는거기때문에 형변환해야함.
    String userid = (String)session.getAttribute("userid");
%>
<html>
<head>
    <title>session</title>
</head>
<body>
<h2>환영합니다 :)</h2>
<p><%=userid%>님 로그인되었습니다.</p>
<p>[<a href="7_session_logout.jsp">로그아웃</a>]</p>
</body>
</html>

 

<%--
    7_session_fail.jsp
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>session</title>
</head>
<body>
<h2>⚠로그인 실패 ️</h2>
<p>아이디 또는 비밀번호를 확인해주세요.</p>
</body>
</html>

 

<%--
    7_session_logout.jsp
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    // 세션 아이디 삭제
    session.invalidate();

    // 다시 로그인 페이지로 이동
    response.sendRedirect("7_session.jsp");
%>
<html>
<head>
    <title>Title</title>
</head>
<body>

</body>
</html>

 

** Application 객체 (공유변수)

  • 특정 웹 어플리케이션에 포함된 모든 JSP 페이지는 하나의 application 기본 객체를 공유 변수
  • application 객체는 웹 어플리케이션 전반에 걸쳐서 사용되는 정보를 담고 있음.

* 생명주기

  • request 객체는 요청 영역마다 생성
  • session 객체는 브라우저 별로 생성
  • application 객체는 프로그램 전체에서 딱 한번 최초 가동시 생성 ( WAS가 한번 실행되면 유지되는 ... )
<%--
    application.jsp
--%>
<%@ page import="java.util.Arrays" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    int total = 0;

    if(application.getAttribute("total_count") != null){
        total = (int)application.getAttribute("total_count");
    }

    application.setAttribute("menu", Arrays.asList("홈","등록","구매","마이페이지"));
    application.setAttribute("total_count", ++total);

%>
<html>
<head>
    <title>application</title>
</head>
<body>
<p><a href="8_application_home.jsp">다음페이지로</a></p>
<p>누적된 총계 : <%=total%></p>
</body>
</html>

 

<%--
    8_application_home.jsp
--%>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    List<String> list = (List)application.getAttribute("menu");
    int total = (int)application.getAttribute("total_count");
%>
<html>
<head>
    <title>application</title>
</head>
<body>
<ul>
    <% for(String menu:list){ %>
        <li><%=menu%></li>
    <%}%>
</ul>
<p><%=total%></p>
</body>
</html>

 

* 예외 페이지

  • 예외 상황이 발생했을 경우 웹 컨테이너(톰켓) 에서 제공하는 기본적인 예외페이지
  • 개발 과정에서는 예외 페이지 또는 에러 코드로 오류를 수정하는데 도움을 받을 수 있음 단, 화면에 보여지면 안됨!
  • 직접 예외 처리
 try{} catch(){}
  • 에러를 처리할 페이지를 따로 지정
<%@ page errorPage="에러가 발생했을 때 보여줄 페이지" %>
  • web.xml
<error-page>
		<error-code>404</error-code>
        <location>/errorpage/error_505.jsp</location>
</error-page>

// exception type
<error-page>
		<exception-type>java.lang.NullPointerException</exception-type>
        <location>/errorpage/error_null.jsp</location>
</error-page>

 

* error 우선순위

  1. 페이지 지시자 태그의 errorPage 속성에 지정한 페이지
  2. web.xml에 지정한 에러타입에 따른 페이지
  3. web.xml에 지정한 응답상태 코드에 따른 페이지
  4. tomcat이 제공하는 에러 페이지
<%--
    errorpage.jsp
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page errorPage="9_errorpage_error.jsp" %>
<html>
<head>
    <title>error page</title>
</head>
<body>
<h2>errorpage</h2>
<p>의도치 않게 에러가 발생했습니다.</p>
<%
    String abc = (String)session.getAttribute("ABC");
    abc.charAt(3);  // 에러 발생!
%>
</body>
</html>

 

<%--
    9_errorpage_error.jsp
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isErrorPage="true" %> <!-- 에러페이지로 사용함 -->

<html>
<head>
    <title>error 🫥</title>
</head>
<body>
<h2>에러 발생!! 🚨🚨🚨🚨</h2>
<p>에러가 발생하셨습니다. 이동해주세요.</p>
<p><a href="./7_session.jsp">이동</a></p>
</body>
</html>

 

* Action Tag

  • JSP 페이지 내에서 동작을 지시하는 태그
  • 이동을 강제하는 forward, 페이지를 삽입하는 include, 값을 지정하는 param, 자바의 클래스와 연동하는 useBean 등 

1. forward 

  • 요청 받은 요청 객체(request)를 위임하는 컴포넌트에 요청 객체값을 동일하게 전달
  • 요청을 처리함과 동시에 해당결과를 바로 보여줘야 하는 경우
<%--
    forward.jsp
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>forward</title>
</head>
<body>
<form method="post" action="10_forward_ok.jsp">
    <p>아이디: <input type="text" name="userid"></p>
    <p><button type="submit">확인</button></p>
</form>
</body>
</html>

 

<%--
    10_forward_ok.jsp
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%-- forward actionTag--%>
<jsp:forward page="10_forward_result.jsp"/>
<html>
<head>
    <title>forward</title>
</head>
<body>

</body>
</html>

 

<%--
    10_forward_result.jsp
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String userid =request.getParameter("userid");
%>
<html>
<head>
    <title>forward</title>
</head>
<body>
<p>전달받은 userid: <%=userid%></p>
</body>
</html>

 

2. sendRedirect

  • 요청 받은 요청객체를 위임하는 컴포넌트에 전달하는 것이 아닌, 새로운 요청 객체를 생성
<%--
    sendRedirect
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>sendRedirect</title>
</head>
<body>
<form method="post" action="10_sendRedirect_ok.jsp">
    <p>아이디: <input type="text" name="userid"></p>
    <p><button type="submit">확인</button></p>
</form>
</body>
</html>

 

<%--
    sendRedirect_ok.jsp
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String userid =request.getParameter("userid");
    // request.setAttribute("userid",userid);   --> 전달안됨 / forward 에선 가능함
    // response.sendRedirect("10_sendRedirect_result.jsp");

%>
<html>
<head>
    <title>forward</title>
    <script>
        window.onload=function(){
            document.getElementById("hiddenValue").value ="<%=userid%>"
            document.getElementById("redirectForm").submit();
        }

        // location.href ='10_sendRedirect_result.jsp?userid=',"<userid>" --> 단, 망가질 수 있음.
    </script>
</head>
<body>
<form id="redirectForm" method="post" action="10_sendRedirect_result.jsp">
    <input type="hidden" id="hiddenValue" name="userid" value="">
</form>
</body>
</html>

 

<%--
    sendRedirect_result.jsp
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    // null만 전달됨
    String userid =request.getParameter("userid");
%>
<html>
<head>
    <title>forward</title>
</head>
<body>
<p>전달받은 userid: <%=userid%></p>
</body>
</html>

 

** Servlet API

<%--
    dispatcher.jsp
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>dispatcher</title>
</head>
<body>
<p><a href="11_dispatcher_ok.jsp?userid=apple">이동</a></p>
</body>
</html>

 

<%--
    11_dispatcher_ok.jsp
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String userid = request.getParameter("userid");

    request.setAttribute("userid",userid);
    request.setAttribute("name","김사과");
    request.setAttribute("age",20);
    request.setAttribute("gender","여자");

    // pom.xml에 servlet api 추가
    RequestDispatcher rd = request.getRequestDispatcher("11_dispatcher_result.jsp");
    // 이동
    rd.forward(request,response);
%>
<html>
<head>
    <title>dispatcher</title>
</head>
<body>

</body>
</html>

API 추가

<%--
    dispatcher_result.jsp
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String userid = (String)request.getAttribute("userid");
    String name = (String)request.getAttribute("name");
    String gender = (String)request.getAttribute("gender");
    int age = (Integer) request.getAttribute("age");
%>
<html>
<head>
    <title>dispatcher</title>
</head>
<body>
<h2>forward로 넘어온 값</h2>
<p>userid: <%=userid%></p>
<p>name: <%=name%></p>
<p>gender: <%=gender%></p>
<p>age: <%=age%></p>

</body>
</html>

 

 

'Backend > Servlet' 카테고리의 다른 글

Tomcat9  (0) 2025.06.10
Servlet  (0) 2025.06.09
Maven 프로젝트  (0) 2025.06.04
Servlet _ Apache Tomcat _ Install  (0) 2025.06.02
Servlet _ NginX _ Install  (0) 2025.06.02