서블릿&JSP/뉴렉쳐 서블릿&JSP강의

[서블릿/jsp] 여러 개의 Submit 버튼 사용 및 입력 데이터 배열로 받기

째로스 2023. 6. 17. 21:56

 

1. 여러 개의 Submit 버튼 사용하기

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="calc" method="post">
		<div>
			<label>x : </label>
			<input type="text" name="x"/>
		</div>
		<div>
			<label>y : </label>
			<input type="text" name="y"/>
		</div>
		<div>
			<input type="submit" name="operator" value="덧셈"/>
			<input type="submit" name="operator" value="뺄셈"/>
		</div>
		<div>
		</div>
	</form>

</body>
</html>

버튼이 2개 생성되며 하나는 value 값이 덧셈, 나머지 하나는 value 값이 뺄셈이다.

버튼 클릭 시 calc라는 서블릿을 실행한다.

@WebServlet("/calc")
public class Calc extends HttpServlet{
	@Override
	protected void service(HttpServletRequest request
			, HttpServletResponse response) throws ServletException, IOException {
		//UTF-8 형식으로 전송하는 것
		response.setCharacterEncoding("UTF-8");
		//웹 브라우저에 UTF-8 형식으로 읽으라고 하는 것
		response.setContentType("text/html; charset=UTF-8");
		//웹 브라우저가 보낸 입력 값을 UTF-8 형식으로 읽어오는 것(필터로 적용시킬 것임)
		//request.setCharacterEncoding("UTF-8");
		
		PrintWriter out = response.getWriter();
		
		String x_ = request.getParameter("x");
		String y_ = request.getParameter("y");
		String op = request.getParameter("operator");
		
		int x = 0;
		if(x_ != null && !x_.contentEquals(""))
			x = Integer.parseInt(x_);
		
		int y = 0;
		if(y_ != null && !y_.contentEquals(""))
			y = Integer.parseInt(y_);
		
		int result = 0;
		if(op.contentEquals("덧셈"))
			result = x+y;
		else
			result = x-y;
		
		
		out.printf("결과 : %d\n",result);
	}
}

 

결과는 아래와 같다.

 

-덧셈 버튼 클릭

버튼의 name을 operator로 지정했었는데, payload에서도 이를 확인할 수 있다.

한글은 2바이트로 되어있기 때문에 위처럼 body에 전송됨을 볼 수 있다.

 

- 뺼셈 버튼 클릭

 

2. 입력 데이터 배열로 받기

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="add2" method="post">
		<div>
		<!-- 같은 name을 쓰면 배열로 보낸다 -->
			<input type="text" name="num"/>
			<input type="text" name="num"/>
			<input type="text" name="num"/>
			<input type="text" name="num"/>
		</div>
		<div>
			<input type="submit" value="덧셈"/>
		</div>
		<div>
		</div>
	</form>

</body>
</html>

form 내의 input type를 모두 같은 name으로 지정하면 배열과 같은 효과를 낼 수 있다.

@WebServlet("/add2")
public class Add2 extends HttpServlet{
	@Override
	protected void service(HttpServletRequest request
			, HttpServletResponse response) throws ServletException, IOException {
		//UTF-8 형식으로 전송하는 것
		response.setCharacterEncoding("UTF-8");
		//웹 브라우저에 UTF-8 형식으로 읽으라고 하는 것
		response.setContentType("text/html; charset=UTF-8");
		//웹 브라우저가 보낸 입력 값을 UTF-8 형식으로 읽어오는 것(필터로 적용시킬 것임)
		//request.setCharacterEncoding("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.printf("결과 : %d\n" ,result);
	}
}

String 배열로 이전에 선언했던 name들을 받아올 수 있다.

 

실행결과는 아래와 같다.