반응형
ServletContext를 통해 저장하고 싶은 value 값을 (key, value) 형태로 저장할 수 있다.
package com.newlec.web;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/calc2")
public class Calc2 extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
PrintWriter out = res.getWriter();
res.setCharacterEncoding("UTF-8");
res.setContentType("text/html; charset=UTF-8");
ServletContext application = req.getServletContext();
String v_ = req.getParameter("v");
String op = req.getParameter("op");
int v=0;
if (!v_.equals("")) v = Integer.parseInt(v_);
if (op.equals("=")) {
int x = (Integer)application.getAttribute("value");
int y = v;
int result=0;
String operator = (String)application.getAttribute("op");
if (operator.equals("+")) result = x+y;
else result = x-y;
out.println("result is "+result);
}
else {
application.setAttribute("value",v);
application.setAttribute("op",op);
}
}
}
반응형
'Back-end > JSP & Servlet' 카테고리의 다른 글
servlet cookie를 이용한 상태 유지 (0) | 2022.07.06 |
---|---|
servlet session객체를 이용한 상태 유지 (0) | 2022.07.06 |
servlet 입력으로 배열 받는 방법 (0) | 2022.07.03 |
servlet utf-8 type 설정 및 serlvet filter 사용 (0) | 2022.07.02 |
servlet 어노테이션을 활용한 url 매핑 (0) | 2022.07.01 |