728x90
상태 유지를 위한 5가지 방법
- application 저장소 : 서블릿 컨텍스트(Context) → 서블릿이라는 것들이 서로 자원을 공유할 수 있는 저장소 역할
- session
- cookie
- hidden input
- querystring
1) 두 개의 숫자를 하나씩 개별적으로 입력받아 연산하기 - application 객체 사용하기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div>
<form action="calc" method="post">
<div>
<label>계산할 값을 입력하세요.</label>
</div>
<div>
<input type="text" name="v">
</div>
<div>
<input type="submit" name="button" value="+">
<input type="submit" name="button" value="-">
<input type="submit" name="button" value="=">
</div>
</form>
</div>
</body>
</html>
package com.jsp.web;
import java.io.IOException;
import java.io.PrintWriter;
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;
@WebServlet("/calc")
public class Calc extends HttpServlet{
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
// 값을 applicationContext 담는 작업
ServletContext application = request.getServletContext();
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
String v_ = request.getParameter("v");
String op = request.getParameter("button");
int v = 0;
if(!v_.equals("")) {
v = Integer.parseInt(v_);
}
// 계산
if(op.equals("=")) {
// 앞에서 저장했던 값 -> applicationContext에 담긴 값들을 꺼내는 작업
// object로 값을 반환하기 때문에 Integer 사용
int x = (Integer)application.getAttribute("value");
// 지금 사용자가 전달한 value 값
int y = v;
String operator=(String)application.getAttribute("op");
int result = 0;
if(operator.equals("+")) {
result=x+y;
}else {
result=x-y;
}
PrintWriter out = response.getWriter();
out.printf("계산 결과는 %d\n입니다.", result);
// 값을 저장
}else {
application.setAttribute("value", v);
application.setAttribute("op", op);
}
}
}
application 전역에서 사용할 수 있다.
2) 두 개의 숫자를 하나씩 개별적으로 입력받아 연산하기 - session 사용하기
package com.jsp.web;
import java.io.IOException;
import java.io.PrintWriter;
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{
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
// 값을 applicationContext 담는 작업
ServletContext application = request.getServletContext();
HttpSession session = request.getSession();
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
String v_ = request.getParameter("v");
String op = request.getParameter("button");
int v = 0;
if(!v_.equals("")) {
v = Integer.parseInt(v_);
}
// 계산
if(op.equals("=")) {
int x = (Integer)session.getAttribute("value");
int y = v;
String operator=(String)session.getAttribute("op");
int result = 0;
if(operator.equals("+")) {
result=x+y;
}else {
result=x-y;
}
PrintWriter out = response.getWriter();
out.printf("계산 결과는 %d\n입니다.", result);
// 값을 저장
}else {
session.setAttribute("value", v);
session.setAttribute("op", op);
}
}
}
session 범주 내에서만 사용할 수 있다.
여기서 session이란 현재 접속한 사용자를 말하며 현재 접속자마다 공간이 달라진다.
→ 크롬창에서 계산한 결과와 엣지창에서의 계산한 결과는 같은 사용자로 인식하지 않는다.
→ 하지만 크롬창 2개에서의 계산한 결과는 같은 사용자로 인식한다.
그렇다면 WAS는 어떻게 현재 사용자(session)을 구분할까?
제일 처음 사용자의 요청이 왔을 때 서블릿의 SID(session id)가 존재하지 않기 때문에
Session 저장소는 사용하지 못하고 Application 저장소만 사용할 수 있다.
서버쪽에서 SID를 부여해주며 SID에 해당하는 공간을 저장소 만든다.
그러고나서 다음 요청을 하면 브라우저는 처음 요청의 SID 값을 가지고 있기 때문에
session 저장에 값을 넣을 수 있게 된다. 이 SID 값이 달라지면 사용자가 달라지게 되는 것이다.
그러고나서 브라우저 창을 닫으면 SID와 Session 저장소는 소멸하게 된다.
※ 참고하기 ※
톰캣이 종료된 후에도 session이 메모리에서 삭제되지 않는 경우
Servers → Tomcat 폴더 → context.xml → <Manager pathname="" /> 부분 주석 해제하기
세션 메소드
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을 시작으로 하는 밀리초)
728x90
'강의 정리하기 > JSP와 Servlet' 카테고리의 다른 글
Service 함수의 GET 메소드와 POST 메소드 (0) | 2023.07.03 |
---|---|
상태 유지를 위한 방법들의 차이점과 페이지 전환 (0) | 2023.03.30 |
예제 (0) | 2023.03.27 |
GET , POST 요청과 필터 (0) | 2023.03.19 |
URL 매핑 및 인코딩 (0) | 2023.03.19 |