본문 바로가기

IT/JSP

JSP 1일차 [계산기]

clac.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>


<%

String re = request.getParameter("result");

%>


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<HTML>

<HEAD>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<TITLE>계산기</TITLE>

</HEAD>


<BODY>


<H3>계산기</H3>

<HR>


<form name=form1 method=post action="calcResult.jsp"> <!-- requert(던지다,요청) -> calcResult -->

<input TYPE="text" NAME="num1" width=200 size="5">

<select NAME = "operator"> <!-- operator -> calcResult로 넘겨줌 -->

<option selected>+</option>

<option>-</option>

<option>*</option>

<option>/</option>

</select>

<INPUT TYPE="text" NAME="num2" width=200 size="5">

<input type="submit" value="계산" name="B1"> <!-- type = submit 은 값을 넘긴다. --> 

<input type="reset" value="다시 입력" name="B2">

</form>

<HR>


계산결과 : <%=re%>


<hr>

</body>

</html>



calcResult.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

    <% int result = 0; 


if(request.getMethod().equals("POST")){

String op = request.getParameter("operator"); // 연산자를 가져옴 calc가 가지고 있는 값을 가져온다 operator

int num1 = Integer.parseInt(request.getParameter("num1"));

int num2 = Integer.parseInt(request.getParameter("num2"));

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

result = num1+num2;

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

result = num1-num2;

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

result = num1*num2;

}

if(op.equals("/")){

result = num1/num2;

}else if(num1 ==0){

result = 0;

}else if(num2 == 0){

result = 0;

}

}

%>


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>

</head>

<body>

<form name=form2 method="POST" action="calc.jsp">

<h1>계산결과 : <%=result%></h1>

<input type="hidden" value=<%=result%> name="result">

<input type="submit" value="dd" name="B1">

</form>

</body>

</html>