<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div align="center">
<h2>학생 정보 입력 화면</h2>
<form action="student" method="post">
<table border="1" cellspacing="0">
<tr>
<th>학 번</th>
<td> <input type="text" name="hakbun"></td>
</tr>
<tr>
<th>이 름</th>
<td> <input type="text" name="name"></td>
</tr>
<tr>
<th>전공과목</th>
<td> <input type="checkbox" name="major" value="java">Java
<input type="checkbox" name="major" value="C언어">C언어
<input type="checkbox" name="major" value="JSP">JSP
<input type="checkbox" name="major" value="Spring">Spring
<input type="checkbox" name="major" value="PHP">PHP
</td>
</tr>
<tr>
<th>연락처</th>
<td> <input type="text" name="phone"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="등록">
<input type="reset" value="취소">
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
major라는 변수 이름으로 체크 박스의 값을 보내준다.
그 후 서블릿에서 request.getParameterValues("major")을 통해 체크박스의 값을 받는다.
getParameterValues의 경우 반환값이 여러 개이므로 배열로 리턴된다.
따라서, 해당 값을 출력하기 위해서는 for문을 사용해야 한다.
package com.sist;
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("/student")
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public StudentServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// method="post" 경우에는 한글 깨짐 현상이 발생함
// 한글이 깨지지 않게 설정
request.setCharacterEncoding("UTF-8");
//1단계: Ex05.jsp 페이지에서 넘어온 데이터들을 처리해주자.
String hakbun = request.getParameter("hakbun");
String name = request.getParameter("name");
String phone = request.getParameter("phone");
String[] major = request.getParameterValues("major");
//2단계: 웹즈라우저에 요청한 결과를 화면에 보여주자.
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("학 번 : " + hakbun +"<br>");
out.println("이 름 : " + name +"<br>");
out.println("전공과목 : ");
for(int i=0; i<major.length; i++) {
out.println(major[i] + " ");
}
out.println("<br>연 락 처 : " + phone +"<br>");
out.println("</body>");
out.println("</html>");
}
}


체크했던 값들이 나오는 것을 볼 수 있고, post 방식이기 때문에 주소창에 변수 값이 나타나지 않는다.
'Back > Servlet' 카테고리의 다른 글
[Servlet] 에노테이션(1:1)등록과 web.xml 파일 등록 (0) | 2021.05.03 |
---|---|
자바 서블릿(Servlet) 기초 (0) | 2021.05.03 |