[Jsp] 계산기(Calculator) 만들기 예제 (Redirect, Dispatch 방식 포함)

o목록



==================================================================================================

web.xml


<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">

  <display-name>calculatorWeb</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  <servlet>

  <servlet-name>CalculatorServlet</servlet-name>

  <servlet-class>calc.controller.CalculatorServlet</servlet-class>

  </servlet>

  

  <servlet-mapping>

  <servlet-name>CalculatorServlet</servlet-name>

  <url-pattern>/calc</url-pattern>

  </servlet-mapping>

</web-app>


==================================================================================================

CalculatorServlet.java


package calc.controller;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import calc.service.CalculatorService;


public class CalculatorServlet extends HttpServlet {


@Override

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//1. 요청파라미터 조회

request.setCharacterEncoding("UTF-8");//요청파라미터 한글처리.

//피연산자 2

String op1 = request.getParameter("op1"); 

String op2 = request.getParameter("op2"); 

//연산자 

String operator = request.getParameter("operator"); 

String result = null;//처리결과를 저장할 변수(성공/실패 메세지)

try{

int operand1 = Integer.parseInt(op1);

int operand2 = Integer.parseInt(op2);

//2.  Business Logic 처리(계산) - 연산자 조건에 따라 계산 처리 (조건-if/switch(문자열 비교는 jdk7부터))

CalculatorService service = CalculatorService.getInstance();

result = service.calculate(operand1, operand2, operator);

/*

if(operator.equals("+")){

result = String.format("결과 : %d %s %d = %d", operand1, operator, operand2, operand1+operand2);

}else if(operator.equals("-")){

result = String.format("결과 : %d %s %d = %d", operand1, operator, operand2, operand1-operand2);

}else if(operator.equals("*")){

result = String.format("결과 : %d %s %d = %d", operand1, operator, operand2, operand1*operand2);

}else if(operator.equals("/")){

result = String.format("결과 : %d %s %d = %d", operand1, operator, operand2, operand1/operand2);

}

*/

}catch(NumberFormatException e){

result = "피연산자는 숫자만 입력하십시요.";

}

//3. 처리결과 응답

// calc_result.jsp 호출(이동) - result값을 전달

//Redirect방식으로 수행을 이동. -> jsp로 보내야 하는 값이 있는 경우 => query string으로 전송

        // -> 영문/숫자 코드값 전송.

//response.sendRedirect("/calculatorWeb/calc_result.jsp?result="+result);

//요청 디스패치 방식 호출(이동) -> jsp로 보내야 하는 값이 있는 경우. 속성을 이용한다.

request.setAttribute("result", result);

RequestDispatcher rdp =  // request.getRequestDispatcher("/calc_result.jsp"); //   / -> application의 root 경로

request.getRequestDispatcher("/WEB-INF/view/calc_result.jsp");

rdp.forward(request, response);

/*

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

out.print("<!doctype html>");

out.print("<html><head><title>계산 결과</title></head>");

out.print("<body>");

out.print(result);

out.print("<p><a href='/calculatorWeb/Calculator-form.html'>계산폼</a>");

out.print("</body></html>");

*/

}

}


==================================================================================================

CalculatorService.java

package calc.service;

public class CalculatorService {
private static CalculatorService instance = new CalculatorService();
public static CalculatorService getInstance(){
return instance;
}
private CalculatorService(){}
public String calculate(int operand1,int operand2, String operator){
String result=null;
if(operator.equals("+")){
result = String.format ("결과 : %d %s %d = %d", operand1, operator, operand2, operand1+operand2);
}else if(operator.equals("-")){
result = String.format ("결과 : %d %s %d = %d", operand1, operator, operand2, operand1-operand2);
}else if(operator.equals("*")){
result = String.format ("결과 : %d %s %d = %d", operand1, operator, operand2, operand1*operand2);
}else if(operator.equals("/")){
result = String.format ("결과 : %d %s %d = %d", operand1, operator, operand2, operand1/operand2);
}
return result;
}
}

==================================================================================================

Calculator-form.html


<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

<form action="/calculatorWeb/calc" method="post">

 피연산자1 : <input type = "text" name="op1" width="200" size="5"><br>

 

 연산자 : <select name="operator">

  <option value="+"> 덧셈 </option>

  <option value="-">뺏셈  </option>

  <option value="*"> 곱하기 </option>

  <option value="/"> 나누기 </option>

  </select><br>

 피연산자2 : <input type = "text" name="op2" width="200" size="5"><br>

 

 <input type="submit" value="계산" name="b1">

 <input type="reset" value="재입력" name="b2">

 

 

 </form>

</body>

</html>


o결과

==================================================================================================

calc_result.jsp


<%@ page contentType="text/html;charset=UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

<h2>계산 결과</h2>

<p>

Redirect로 이동 : <%= request.getParameter("result") %><br> <!-- 웹브라우저 상에 출력해라. -->

요청디스패치 이동 : <%=request.getAttribute("result") %> <!-- request.getAttribute("이름") Request객체에 저장된 속성중 이름이 "이름" 인속성 조회 -->

</p>


<a href="/calculatorWeb/Calculator-form.html">계산 폼</a>

</body>

</html>


o결과


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

[JSP/Servlet] Form 예제  (0) 2017.05.10
[JSP/Servlet] Session 관리  (0) 2017.05.10
[Tomcat] 설치 메뉴얼 자료  (0) 2017.05.10
[JSP/Servlet] Listener / Attribute  (0) 2017.05.10
[JSP/Servlet] ServletContext/ServletConfig  (0) 2017.05.09

댓글

Designed by JB FACTORY