ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 계산기 프로그램 하나의 서블릿으로 합치기 (오류 수정 완)
    JSP, Servlet 2021. 12. 14. 01:03

    https://leeyun.tistory.com/180

     

    계산기 서블릿 구현하기 (오류 수정 완)

    동적인 페이지(서버 페이지)의 필요성 사용자가 입력한 숫자를 포함한 웹 페이지를 보내줘야 함 -> 동적으로 만들어야 함 처음이자 마지막으로 동적인 페이지 서블릿으로 직접 만들기 im

    leeyun.tistory.com


    GET/POST에 특화된 서비스 함수

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    //"GET"과 "POST"는 반드시 대문자로 입력해야 함
    if(request.getMethod().equals("GET")) {
    System.out.println("GET 요청이 왔습니다.");
    } else if(request.getMethod().equals("POST")) {
    System.out.println("POST 요청이 왔습니다.");
    }
    
    //doGET() 또는 doPost() 호출하는 역할, 두 메소드가 Override 되어있지 않으면 오류가 남
    super.service(request, response);
    }

     

    계산기 프로그램 하나의 서블릿으로 합치기
    CalcPage를 doGet() 메소드로
    Cala를 doPost() 메소드로 보내고
    doPost()에 expCookie의 setPath /calculator 로 지정

     

    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.script.ScriptEngine;
    import javax.script.ScriptEngineManager;
    import javax.script.ScriptException;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    @WebServlet("/calculator")
    public class Calculator extends HttpServlet{
    	
    	@Override
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		PrintWriter out = response.getWriter();
    		Cookie[] cookies = request.getCookies();
    		
    		String exp = "0";
    		if(cookies != null) 
    			for(Cookie c : cookies) 
    				if(c.getName().equals("exp")) {
    					exp = c.getValue();
    					break;
    				}
    			
    		out.write("<!DOCTYPE html>");
    		out.write("<html>");
    		out.write("<head>");
    		out.write("<meta charset='UTF-8'>");
    		out.write("<meta name='viewport' content='width=device-width, initial-scale=1.0'>");
    		out.write("<title></title>");
    		out.write("<style>");
    		out.write("input{");
    		out.write("width: 50px;");
    		out.write("height: 50px;");
    		out.write("}");
    		out.write(".output{");
    		out.write("width: 50px;");
    		out.write("background-color: #e9e9e9;");
    		out.write("font-size: 24px;");
    		out.write("font-weight: bold;");
    		out.write("text-align: right;");
    		out.write("padding: 0px 5px;");
    		out.write("}");
    		out.write("</style>");
    		out.write("</head>");
    		out.write("<body>");
    		out.write("<form method='post'>");
    		out.write("<table>");
    		out.write("<tr>");
    		out.printf("<td class='output' colspan='4'>%s</td>", exp);
    		out.write("</tr>");
    		out.write("<tr>");
    		out.write("<td><input type='submit' name='operator' value='CE'/></td>");
    		out.write("<td><input type='submit' name='operator' value='C'/></td>");
    		out.write("<td><input type='submit' name='operator' value='BS'/></td>");
    		out.write("<td><input type='submit' name='operator' value='/'/></td>");
    		out.write("</tr>");
    		out.write("<tr>");
    		out.write("<td><input type='submit' name='value' value='7'/></td>");
    		out.write("<td><input type='submit' name='value' value='8'/></td>");
    		out.write("<td><input type='submit' name='value' value='9'/></td>");
    		out.write("<td><input type='submit' name='operator' value='*'/></td>");
    		out.write("</tr>");
    		out.write("<tr>");
    		out.write("<td><input type='submit' name='value' value='4'/></td>");
    		out.write("<td><input type='submit' name='value' value='5'/></td>");
    		out.write("<td><input type='submit' name='value' value='6'/></td>");
    		out.write("<td><input type='submit' name='operator' value='-'/></td>");
    		out.write("</tr>");
    		out.write("<tr>");
    		out.write("<td><input type='submit' name='value' value='1'/></td>");
    		out.write("<td><input type='submit' name='value' value='2'/></td>");
    		out.write("<td><input type='submit' name='value' value='3'/></td>");
    		out.write("<td><input type='submit' name='operator' value='+'/></td>");
    		out.write("</tr>");
    		out.write("<tr>");
    		out.write("<td></td>");
    		out.write("<td><input type='submit' name='value' value='0'/></td>");
    		out.write("<td><input type='submit' name='dot' value='.'/></td>");
    		out.write("<td><input type='submit' name='operator' value='='/></td>");
    		out.write("</tr>");
    		out.write("</table>");
    		out.write("</form>");
    		out.write("</body>");
    		out.write("</html>");
    	}
    	
    	@Override
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		Cookie[] cookies = request.getCookies();
    		
    		String value = request.getParameter("value");
    		String operator = request.getParameter("operator");
    		String dot = request.getParameter("dot");
    		
    		String exp = "";
    		if(cookies != null) 
    			for(Cookie c : cookies) 
    				if(c.getName().equals("exp")) {
    					exp = c.getValue();
    					break;
    				}
    		
    		if(operator != null && operator.equals("=")) {
    			ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
    			try {
    				exp = String.valueOf(engine.eval(exp));
    			} catch (ScriptException e) {
    				e.printStackTrace();
    			}
    			
    		} else if(operator != null && operator.equals("C")) { 
    			exp = "";
    			
    		} else {
    			exp += (value == null) ? "" : value;
    			exp += (operator == null) ? "" : operator;
    			exp += (dot == null) ? "" : dot;
    		}
    		
    		Cookie expCookie = new Cookie("exp", exp);
    		
    		if(operator != null && operator.equals("C"))
    			expCookie.setMaxAge(0);
    		
    		expCookie.setPath("/youtube_lecture/calculator");
    		response.addCookie(expCookie);	
    		response.sendRedirect("calculator");
    	}
    }

     

    오류 내용은 맨 위 게시글에 명시된 오류와 같았음

    doPost() 메소드에서 expCookie.setPath를 설정할 때 영상에서는 /calculator 로 지정하지만

    내 url은 http://localhost:8080/youtube_lecture/calculator 이기 때문에

    expCookie.setPath를 /youtube_lecture/calculator 로 설정하여 해결함

    댓글