본문 바로가기

Java

Session 객체와 상태 관리

반응형

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.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();

		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 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("result is %d\n", result);
		} else {
//			값을 저장
//			application.setAttribute("value", v);
//			application.setAttribute("op", op);
			session.setAttribute("value", v);
			session.setAttribute("op", op);
		}

	}
}

 

 

 

 

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

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

 

반응형

'Java' 카테고리의 다른 글

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