본문 바로가기

Servlet&JSP

Servlet의 상태값 유지하기1 - Application Scope

 

 

기본예제와 같이 단순히 두 값을 동시에 받아 사칙연산 결과를 결과페이지에 출력하는 서블릿은 

따로 값을 유지할 필요가 없다.

 

 

하지만 값 하나를 먼저 받고 서블릿에 전달한 뒤, 후속값을 받는 경우

먼저받는값을 페이지 이동후에도 어딘가에 저장해놓을 필요성이 생긴다.

 

이럴땐 하나의 web application 전체를 관리하는 ServletContext 객체를 활용해서 해결할 수 있다.

 

@WebServlet("/Cal_App")
public class Cal_App extends HttpServlet {
 
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
 
        PrintWriter out = resp.getWriter();
        String v_ = req.getParameter("v");
        String op = req.getParameter("operator");
 
        ServletContext app = req.getServletContext();
 
        int v = 0;
        if(!v_.equals(""))
            v = Integer.parseInt(v_);
        //계산
        if (op.equals("=")) {
 
            int x = (Integer)app.getAttribute("value");
            int y = v;
            String operator = (String)app.getAttribute("op");
 
            int result = switch (operator) {
                case "+" -> result = x + y;
                case "-" -> result = x - y;
                case "x" -> result = x * y;
                default -> result = x / y;
            };
            out.println("result is "+result);
        } else {
            //값 저장
            app.setAttribute("value", v);
            app.setAttribute("op", op);
            resp.sendRedirect("/Application.jsp");
        }
    }
}
 
cs

 

- checklist

ServletContext app = req.getServletContext();

ServletContext객체를 생성하고 추출하는 메소드 getServletContext() 사용

 

setAttribute() getAttribute()

받은값 저장, 불러오는 메소드

 

if (op.equals("="))

'+','-','x','/' 버튼을 눌렀을땐 다음값을 받고나서 연산을 해야하기 때문에 

else문의 setAttribute() 메소드를 사용하여 받은값을 저장한다.

 

'=' 버튼을 눌렀을때 앞에서 저장한값과 현재 입력한 값을 연산하는 if문 안쪽의 switch문을 실행한다.

 

resp.sendRedirect("/Application.jsp")

값을 저장하는 로직에서는 화면단에 표시할 내용이없어 하얀 화면만 출력된다.

연산을 이어가려면 다시 입력화면으로 돌아와야하는데

편의를 위해 저장 후 sendRedirect() 메소드를 통해 자동으로 돌아오게 설정한다.

'Servlet&JSP' 카테고리의 다른 글

MVC model 개념  (0) 2021.12.17
Servlet의 상태값 유지하기3 - Cookie  (0) 2021.12.14
Servlet의 상태값 유지하기2 - Session Scope  (0) 2021.12.14
간단한 Servlet 예제 구현  (0) 2021.12.07
intelliJ에서 Servlet 기본세팅  (0) 2021.12.05