이번에는 덧셈 연산 뿐 아니라 뺄셈 연산도 가능하도록 Submit 버튼을 두개로 연동해본다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Calculation</title>
</head>
<body>
<div>
<form action="calc" method="post">
<div>
<label>x : </label><input name="x" type="text">
</div>
<div>
<label>y : </label><input name="y" type="text">
</div>
<div>
<input type="submit" name="operator" value="덧셈"/>
<input type="submit" name="operator" value="뺄셈"/>
</div>
</form>
</div>
</body>
</html>
버튼 이름이 같더라도 선택되는 것에 따라 전달되는 value가 다름
package com.newlecture.web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/calc")
public class Calc extends HttpServlet{
@Override
protected void service(HttpServletRequest request
, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
String x_ = request.getParameter("x");
String y_ = request.getParameter("y");
String op = request.getParameter("operator");
int x = 0;
int y = 0;
if(x_ != null && x_ != "") {
x = Integer.parseInt(x_);
}
if(y_ != null && y_ != "") {
y = Integer.parseInt(y_);
}
if(op.equals("덧셈")) {
out.println("덧셈 결과 = " + (x + y));
} else {
out.println("뺄셈 결과 = " + (x - y));
}
}
}
변수의 이름을 같게 설정하면 배열로 값이 전달 됨
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Registration</title>
</head>
<body>
<div>
<form action="add2" method="post">
<div>
<input name="num" type="text">
<input name="num" type="text">
<input name="num" type="text">
<input name="num" type="text">
</div>
<div>
<input type="submit" value="계산"/>
</div>
</form>
</div>
</body>
</html>
package com.newlecture.web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/add2")
public class Add2 extends HttpServlet{
@Override
protected void service(HttpServletRequest request
, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
String[] num_ = request.getParameterValues("num");
int result = 0;
for(int i = 0; i < num_.length; i++) {
int num = Integer.parseInt(num_[i]);
result += num;
}
out.println("덧셈 결과 = " + result);
}
}
같은 이름으로 전달된 값들을 배열로 받아 연산