ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Session 객체로 상태 값 저장하기
    JSP, Servlet 2021. 12. 12. 22:52


        - session은 현재 접속한 사용자 -> 현재 접속자마자 공간이 달라짐
            브라우저가 다르면 사용자를 달리 인식해서 세션이 달라짐
        
    WAS가 현재 사용자(session)를 구분하는 방식
        - 브라우저를 이용해 서버에 요청,
        서버에는 사용자 요청을 수반해 처리하다가 공유하고 싶은 내용은 따로 저장 -> application
        사용자마다 session 공간이 따로 있음
        개인별 마다 번호가 따로 있어서, 
        요청이 처음 왔을 경우에는 사용자는 새로운 사용자가 됨 -> 사용자를 위한 세션 x
        session은 사용자가 아이디를 갖고 있고 세션 아이디를 갖고 있는 사람만 공간에 값을 넣을 수 있음
        처음에는 session은 못 쓰고 application만 사용 가능
        집에 갈 때 아이디를 하나 부여해줌 -> 그 번호에 해당하는 session 생성되고 저장소 마련
        다음에 또 요청할 때 그 번호를 가져와서 session을 사용할 수 있음
        브라우저가 달라지면 번호 없이 요청하게 됨
        브라우저를 닫았다 다시 열어도 사라짐

        void setAttribute(String name, Object value) : 지정된 이름으로 객체를 설정
        Object getAttribute(String name) : 지정한 이름의 객체를 반환
        void invalidate() : 세션에서 사용되는 객체들을 바로 해제
        void setMaxInactiveInterval(int interval) : 세션 타임아웃을 정수(초)로 설정
        boolean isNew() : 세션이 새로 생성되었는지를 확인
        Long getCreationTime() : 세션이 시작된 시간을 반환, 1970년 1월 1일을 시작으로 하는 밀리초
        long getLastAccessedTime() : 마지막 요청 시간, 1970년 1월 1일을 시작으로 하는 밀리초

     


    Application 객체에서 작성한 코드 중 일부만 수정

    <!DOCTYPE html>
    <html>
    <head>
    	<meta charset="UTF-8">
    	<meta name="viewport" content="width=device-width, initial-scale=1.0">
    	<title>과제</title>
    </head>
    <body>
    	<form action="calc" method="post">
    		계산할 값을 입력 하세요. <br>
    		<div>
    			<label>입력 : </label>
    			<input type="text" name="value" />
    		</div>
    		<div>
    			<input type="submit" name="operator" value="+"/>
    			<input type="submit" name="operator" value="-"/>
    			<input type="submit" name="operator" value="="/>
    		</div>
    	</form>
    	
    </body>
    </html>
    import java.io.IOException;
    
    import javax.servlet.ServletContext;
    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 javax.servlet.http.HttpSession;
    
    
    @WebServlet("/calc")
    public class Calc extends HttpServlet {
    	
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		request.setCharacterEncoding("utf-8");
    		response.setCharacterEncoding("utf-8");
    		response.setContentType("text/html; charset=utf-8");
    		
    		ServletContext application = request.getServletContext();
    		HttpSession session = request.getSession();
    		
    		String v_ = request.getParameter("value");
    		String op = request.getParameter("operator");
    		
    		int v = 0;
    		
    		if(!v_.equals("")) {
    			v = Integer.parseInt(v_);
    		}
    		
    		//계산
    		if(op.equals("=")) {
    			
    			//int x = (Integer)application.getAttribute("value");
    			int x = (Integer)session.getAttribute("value");
    			int y = v;
    			//String operator = (String)application.getAttribute("op");
    			String operator = (String)session.getAttribute("op");
    			int result = 0;
    			
    			if(operator.equals("+")) {
    					result = x+y;
    			} else {
    					result = x-y;
    			}
    			
    			response.getWriter().printf("결과는 %d입니다. \n", result);
    		//값을 저장
    		} else {
    			//application.setAttribute("value", v);
    			//application.setAttribute("op", op);
    			session.setAttribute("value", v);
    			session.setAttribute("op", op);
    		}		
    	}
    }

     

    댓글