계산기 화면 구현인 HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>계산기-userBean</title>
</head>
<body>
<h2>계산기-userBean</h2>
<hr>
<form method="post" action="calc.jsp">
<!--서버에 똑같은 환경에서 돌아가기 때문에 세션과 같은 그런 환경 정보-->
<input type="text" name="n1" size="10"> <select name="op">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select> <input type="text" name="n2" size="10">
<input type="submit" value="실행">
</form>
</body>
</html>
자바 빈 객체 생성
package ch07;
public class Calculator {
private int n1;
private int n2;
private String op;
public int getN1() {
return n1;
}
public void setN1(int n1) {
this.n1 = n1;
}
public int getN2() {
return n2;
}
public void setN2(int n2) {
this.n2 = n2;
}
public String getOp() {
return op;
}
public void setOp(String op) {
this.op = op;
}
public long calc() {
long result = 0;
switch(op) {
case "+": result = n1+n2;break;
case "-": result = n1-n2;break;
case "/": result = n1/n2;break;
case "*": result = n1*n2;break;
}
return result;
}
}
jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<jsp:useBean id="mm" class="ch07.Calculator" />
<%-- <jsp:setProperty name="calc" property="*" /> --%>
<!-- html의 name 속성의 값을 받아서 Bean의 setter함수를 호출하여 변수에 저장함 -->
<!-- 주의할점: 변수 이름은 UI에서 넘어오는 name 속성과 똑같아야해 (매개변수 이름이 같아야한다) -->
<!-- html의 name 속성명과 클래스의 변수명은 동일하다. -->
<jsp:setProperty name="mm" property="n1" />
<jsp:setProperty name="mm" property="op" />
<jsp:setProperty name="mm" property="n2" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>계산기 userBean</title>
</head>
<body>
<h2>계산 결과-userBean</h2>
<hr>
결과: <%=mm.calc() %>
</body>
</html>