Java
Session 객체와 상태 관리
liufeier
2021. 9. 2. 15:11
반응형
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
반응형