JSP/Servlet | 클라이언트와 서버 사이의 값 전달 | 폼(form) 전송

사용자으로부터 입력을 받으려면, 역시 기본은 “폼(form) 전송"이다. <form> 태그에 의한 양식에 정보를 담아 전송하고 그 전송에 대한 결과를 받아 처리하는 것이다. HTML의 기본이라 할 수 있는 기능이다.

폼에서 전송된 텍스트는 “getParameter"을 이용하여 얻을 수 있다. 아래와 같은 방식이다.

String 변수 = request.getParameter(이름);

이것으로 폼에 마련된 컨트롤에서 인수에 지정된 이름의 항목의 값을 얻어 올 수 있다. 주의해야 할 것은 “지정하는 것은 ID가 아닌 이름이다"라는 점이다. <input id="hoge">와 같이, ID만 지정하면 값을 얻어 올 수 없다. 반드시 name 속성을 지정해야 한다.

또한, 같은 이름(name)의 항목이 다수 있는 경우에는 그 값을 한꺼번에 얻어 올 수 있다. 이는 ‘getParameterValues’라는 메소드를 사용한다.

String[] 변수 = request.getParameterValues(이름);

이 getParameterValues는 인수로 지정된 name의 값을 모두 모와서 String 배열을 돌려준다. 이는 예를 들어. 여러 항목을 선택할 수 <select> 태그에서 전체 값을 얻우 올 때에 사용된다.

그럼 예제를 만들어 보도록 하자.

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%
String inpt = request.getParameter("input");
inpt = inpt == null ? "" : inpt;
String chk = request.getParameter("check");
chk = chk == null ? "OFF" : "ON";
String rd = request.getParameter("radio");
rd = rd == null ? "" : rd;
String[] sels = request.getParameterValues("select");
String sel = "";
if (sels != null){
    for(int i = 0;i < sels.length;i++)
        sel += sels[i] + " ";
}
String str = "INPUT:" + inpt + "<br>" +
        "CHECK: " + chk + "<br>" +
        "RADIO: " + rd + "<br>" +
        "SELECT:" + sel;
%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Sample jsp</title>
    <style>
    h1 {font-size:16pt; background:#AAFFAA; padding:5px; }
    </style>
</head>
<body>
    <h1>Sample jsp page</h1>
    <p>이 페이지는 샘플입니다.</p>
    <p><%=str  %></p>
    <table>
    <form method="post" action="hello.jsp">
        <tr><td>입력</td><td>
        <input type="text" id="input" name="input"></td></tr>
        <tr><td></td><td>
        <input type="checkbox" id="c1" name="check" value="Une">
        <label for="c1">체크 박스</label></td></tr>
        <tr><td></td><td>
        <input type="radio" name="radio" id="r1" value="first">
        <label for="r1">라디오 버튼1</label><br>
        <input type="radio" name="radio" id="r2" value="Second">
        <label for="r2">라디오 버튼2</label></td></tr>
        <tr><td></td><td>
        <select id="select" name="select" multiple>
            <option value="Eins">첫번째</option>
            <option value="Twei">두번재</option>
            <option value="Drei">세번째</option>
        </select></td></tr>
        <tr><td></td><td>
        <input type="submit" value="전송"></td></tr>
    </form>
    </table>
    </body>
</html>

위에 예제는 양식을 자신의 주소로 보내하여 입력된 정보를 함께 표시하는 예제이다. 여기에서는 hello.jsp라는 파일명으로 만들었기 때문에, 다른 파일 이름을 사용하는 경우는 <form> 태그의 action을 수정한다.

여기에서는 전송된 양식(<select> 이외의)의 정보는 getParameter을 사용하여 얻어오고 있다.

String inpt = request.getParameter("input");
String chk = request.getParameter("check");
String rd = request.getParameter("radio");

모두 name으로 지정한 이름을 인수로 지정하고 있다는 것을 알 수 있을 것이다. 조금 까다로운 것이 <select>에서 얻어 오는 거다. 이는 이번에 여러 항목을 선택할 수 있도록 되어있다.

String[] sels = request.getParameterValues("select");
String sel = "";
if (sels != null){
    for(int i = 0;i < sels.length;i++)
        sel += sels[i] + " ";
}

먼저 getParameterValues에서 String 배열을 얻어온다. 그리고 반복하여 배열에서 한 개씩 값을 얻어오고 있다. 여기서 전혀 값이 없다면, getParameterValues는 null이 되면 for 문은 에러가 되기 때문에 null이 아닌지 확인하고 실행하는 것을 잊지 않도록 하자.




최종 수정 : 2017-12-17