Servlet / JSP ) 7. 상태 유지의 필요성(간단한 계산기)

60jong·2022년 6월 14일
0

Servlet / JSP

목록 보기
7/17

Server 공부 흐름

[Servlet] --HTML코드 출력 문제--> JSP --스파게티 코드 문제--> JSP MVC -> Spring MVC -> SpringBoot


간단한 더하기 계산기 만들기

'한 번에 여러 인자' 계산기

인자 두 개를 받은 뒤, + / - 버튼을 누르면 두 인자를 계산 값을 출력한다.

인자를 받을 페이지는 add.html로 하고 Add Servlet을 만든다.
post요청으로 인자를 넘기기에 Add Servlet은 doPost함수로 받는다.

add.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add</title>
</head>
<body>
  <form action="add" method="post">
      <div>
          <input type="text" name="op1"/>
          <input type="text" name="op2"/>
      </div>
      <div>
          <input type="submit" name = "op" value="+"/>
          <input type="submit" name = "op" value="-"/>
      </div>
  </form>
</body>
</html>

Add.java

@WebServlet("/add")
public class Add extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String op = request.getParameter("op");
        String[] _num = request.getParameterValues("num");

        int result = 0;

        if(op.equals("+"))
            for(String n : _num) {
                if(n!=null && !n.equals(""))
                    result += Integer.parseInt(n);
            }
        if(op.equals("-")) {
            result = Integer.parseInt(_num[0]);
            for (int i = 0; i < _num.length; i++) {
                if(i==0)
                    continue;
                if(_num[i] !=null && !_num[i].equals(""))
                    result -= Integer.parseInt(_num[i]);
            }
        }


        response.getWriter().printf("Result is %d\n",result);

    }
}


상태 유지의 필요성

조각나있는 서버 프로그램인 Servlet들이 종료된 후에도 유지할 수 있는, 공유할 수 있는 데이터가 필요하다면 상태 유지가 필요하다. 상태 유지를 위해서 Servlet은 다음과 같은 객체를 이용한다.

  • Application 객체
  • Session 객체
  • Cookie 객체

Application 객체

WAS에서는 요청에 의해 실행된 Servlet 객체는 실행하며 응답한 뒤에 바로 소멸한다. 그래서 Servlet끼리 정보를 주고 받는 것이 불가능하다. 그래서 Application 객체, Servlet Context라고도 부르며 Servlet끼리 정보를 주고 받게 해주는 저장소로서 이용할 수 있다.

Java 코드 내에서는 ServletContext객체로서 존재하며 request.getServletContext()로 호출 가능하다.


상태 유지 계산기

Application객체를 통해 상태 유지를 이용해서 인자를 저장하고 다시 꺼낼 수 있도록 해서
상태 유지 계산기를 구현해봤다.

Calc.java

@WebServlet("/calc")
public class Calc extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
    		throws ServletException, IOException {
        ServletContext application = request.getServletContext();

        String _value = request.getParameter("value");
        String op = request.getParameter("op");

        int result = 0;
        int value = (_value!= null && !_value.equals("")) 
        		? Integer.parseInt(_value) : 0;

        if(op.equals("=")) {
            int sum = (int) application.getAttribute("value");
            String prevOp = (String) application.getAttribute("op");

            if (prevOp.equals("+"))
                result = sum + value;
            else
                result = sum - value;

            response.getWriter().printf("Result is %d",result);
        } else {
            application.setAttribute("value", value);
            application.setAttribute("op", op);
        }
    }
}

인자를 하나씩 넘겨도 ServletContext 객체에 그 인자가 저장됐다가 "=" 클릭시 호출돼 연산에 사용됐음을 확인할 수 있다.

profile
울릉도에 별장 짓고 싶다

0개의 댓글