본문 바로가기

Java

Cookie와 상태 관리

반응형

Calc2.java

package com.newlectrue.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.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/calc2")
public class Calc2 extends HttpServlet {

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");

		ServletContext application = request.getServletContext();

		HttpSession session = request.getSession();

//		쿠키 불러오기
		Cookie[] cookies = request.getCookies();

		String v_ = request.getParameter("v");
		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 x = 0;

			for (Cookie c : cookies) {
				if (c.getName().equals("value")) {
					x = Integer.parseInt(c.getValue());
					break;
				}
			}

			int y = v;
//			String operator = (String) application.getAttribute("op");
//			String operator = (String) session.getAttribute("op");

			String operator = "";

			for (Cookie c : cookies) {
				if (c.getName().equals("op")) {
					operator = c.getValue();
					break;
				}
			}

			int result = 0;

			if (operator.equals("+")) {
				result = x + y;
			} else {
				result = x - y;
			}

			response.getWriter().printf("result is %d\n", result);
		} else {
//			값을 저장
//			application.setAttribute("value", v);
//			application.setAttribute("op", op);
//			session.setAttribute("value", v);
//			session.setAttribute("op", op);

//			쿠키는 문자열만 저장됨
			Cookie valueCookie = new Cookie("value", String.valueOf(v));
			Cookie opCookie = new Cookie("op", op);
			response.addCookie(valueCookie);
			response.addCookie(opCookie);
		}

	}
}

 

 

 

https://youtu.be/ONtMvVocGy8?list=PLq8wAnVUcTFVOtENMsujSgtv2TOsMy8zd 

 

반응형

'Java' 카테고리의 다른 글

doGet(), doPost()  (0) 2021.09.02
쿠키 메소드 - setPath(), setMaxAge()  (0) 2021.09.02
Session 객체와 상태 관리  (0) 2021.09.02
application 객체와 상태 관리  (0) 2021.09.02
필터 어노테이션을 이용한 한글 출력  (0) 2021.09.02