-
Servlet과 JSP간 데이터 전달 - RequestDispatcher웹 Web/JSP & Servlet 2023. 2. 7. 15:55
신청폼에서 받은 아이디를 다시 신청폼에 띄우기
구조는 form.jsp -> FormServlet.java -> form.jsp
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0"> <display-name>ServletWeb</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.jsp</welcome-file> <welcome-file>default.htm</welcome-file> </welcome-file-list> <servlet> <servlet-name>form</servlet-name> <servlet-class>bitedu.lesson.form.FormServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>form</servlet-name> <url-pattern>/form</url-pattern> </servlet-mapping> </web-app>FormServlet.java
public class FormServlet extends HttpServlet{ @Override public void init() throws ServletException { System.out.println(" = FormServlet init = "); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); String userId = req.getParameter("userId"); String userPw = req.getParameter("userPw"); String[] langs = req.getParameterValues("lang"); String ide = req.getParameter("ide"); String role = req.getParameter("role"); String pCount = req.getParameter("pCount"); String introduce = req.getParameter("introduce"); // 콘솔창 출력 System.out.println("ID = " + userId); System.out.println("비밀번호 = " + userPw); System.out.print("사용언어 = "); for (String lang : langs) { System.out.print(lang + " "); } System.out.println(); System.out.println("사용ide = " + ide); System.out.println("role = " + role); System.out.println("프로젝트 참여 횟수 = " + pCount); System.out.println("자기소개 = " + introduce); // 사용자 아이디 보내기 ------------------------------------------ req.setAttribute("userId", userId); // 요청이 새로 생김 - userId 전달 안됨 // resp.sendRedirect("./input/form.jsp"); // client가 보낸 요청을 그대로 이어서 보내기 - req를 내부적으로 연결 String url = "./input/form.jsp"; RequestDispatcher rd = req.getRequestDispatcher(url); rd.forward(req, resp); } }form.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Form Elements</title> <!-- css파일 로드 방법1 --> <style> @import url("../css/FormCss.css"); </style> <!-- css파일 로드 방법2 --> <link rel="stylesheet" type="text/css" href="../css/FormCss.css"> <!-- js파일 로드 --> <script src="../js/FormJs.js"></script> </head> <body> <% // getAttribute는 object를 리턴하므로 String으로 타입캐스팅 String userId = (String) request.getAttribute("userId"); if(userId==null) { userId = ""; } %> <!-- 3x2 테이블에 폼 요소 넣기 --> <form action="../form" method="post"> <table border=1> <tr> <th>ID </th> <td> <input type="text" id="userId" name="userId" value="<%= userId %>"> <input type="button" value="id체크" onclick="idCheck()"> <span id="idCheckMsg"></span> </td> </tr> <tr> <th>비밀번호 </th> <td> <input type="password" id="pw1" name="userPw"> </td> </tr> <tr> <th>비밀번호 확인</th> <td> <input type="password" id="pw2"> <input type="button" value="비밀번호 체크" onclick="pwCheck()"> <span id="pwCheckMsg"></span> </td> </tr> <tr> <th>사용언어</th> <td> <input type="checkbox" name="lang" class="lang" onclick="checkCount()" value="java">java <input type="checkbox" name="lang" class="lang" onclick="checkCount()" value="python">python <input type="checkbox" name="lang" class="lang" onclick="checkCount()" value="javascript">javascript <input type="checkbox" name="lang" class="lang" onclick="checkCount()" value="html">html <span id="langCntMsg"></span> </td> </tr> <tr> <th>사용IDE</th> <td> <input type="radio" name="ide" onclick="selectedIde()" value="Eclipse">Eclipse <input type="radio" name="ide" onclick="selectedIde()" value="IntelliJ">IntelliJ <input type="radio" name="ide" onclick="selectedIde()" value="Visual Studio">Visual Studio <input type="radio" name="ide" onclick="selectedIde()" value="VS Code">VS Code </td> </tr> <tr> <th>Role</th> <td> <select id="role" name="role"> <option>--- 역할 --- <option value="디자이너">디자이너 <option value="프로그래머">프로그래머 <option value="설계">설계 <option value="개발자">개발자 <option value="퍼블리셔">퍼블리셔 </select> <input type="button" value="선택한 역할 확인" onclick="selectedRole()"> </td> </tr> <tr> <th>프로젝트 참여 횟수</th> <td> <select id="pCount" onchange="selectedPCount(this.value)" name="pCount"> <option>--- 횟수 --- <option value="0회">0회 <option value="1회">1회 <option value="2회">2회 <option value="3회">3회 <option value="4회 이상">4회 이상 </select> </td> </tr> <tr> <th>자기소개</th> <td><textarea cols="30" rows="5" name="introduce">자기소개를 입력하세요</textarea></td> </tr> <tr> <td id="btn" colspan="2"> <input type="reset" value="새로고침"> <input type="submit" id="btn_submit" value="제출"> </td> </tr> </table> </form> </body> </html>

신청폼에서 받은 정보 전부를 다시 신청폼에 띄우기
web.xml은 동일
FormDto.java
-> 폼에서 입력한 데이터를 담을 클래스.
기능이 DTO와 비슷한 것 같아 나는 dto라고 이름붙였는데 강사님은 VO라고 이름 붙이셨다.
public class FormDto { String userId; String userPw; String[] langs; String ide; String role; String pCount; String introduce; public FormDto(String userId, String userPw, String[] langs, String ide, String role, String pCount, String introduce) { this.userId = userId; this.userPw = userPw; this.langs = langs; this.ide = ide; this.role = role; this.pCount = pCount; this.introduce = introduce; } public String getUserId() { return userId; } public String getUserPw() { return userPw; } public String[] getLangs() { return langs; } public String getIde() { return ide; } public String getRole() { return role; } public String getpCount() { return pCount; } public String getIntroduce() { return introduce; } @Override public String toString() { return "FormDto [userId=" + userId + ", userPw=" + userPw + ", langs=" + Arrays.toString(langs) + ", ide=" + ide + ", role=" + role + ", pCount=" + pCount + ", introduce=" + introduce + "]"; } }FormServlet.java
public class FormServlet extends HttpServlet{ @Override public void init() throws ServletException { System.out.println(" = FormServlet init = "); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); String userId = req.getParameter("userId"); String userPw = req.getParameter("userPw"); String[] langs = {"","","",""}; String[] temps = req.getParameterValues("lang"); for (String temp : temps) { langs[Integer.parseInt(temp)] = temp; } String ide = req.getParameter("ide"); String role = req.getParameter("role"); String pCount = req.getParameter("pCount"); String introduce = req.getParameter("introduce"); FormDto dto = new FormDto(userId, userPw, langs, ide, role, pCount, introduce); req.setAttribute("datas", dto); // 요청이 새로 생김 - userId 전달 안됨 // resp.sendRedirect("./input/form.jsp"); // client가 보낸 요청을 그대로 이어서 보내기 - req를 내부적으로 연결 String url = "./input/form.jsp"; RequestDispatcher rd = req.getRequestDispatcher(url); rd.forward(req, resp); } }form.jsp
<%@page import="bitedu.lesson.form.FormDto"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Form Elements</title> <!-- css파일 로드 방법1 --> <style> @import url("../css/FormCss.css"); </style> <!-- css파일 로드 방법2 --> <link rel="stylesheet" type="text/css" href="../css/FormCss.css"> <!-- js파일 로드 --> <script src="../js/FormJs.js"></script> </head> <body> <% // getAttribute는 object를 리턴하므로 타입캐스팅 FormDto datas = (FormDto) request.getAttribute("datas"); if(datas == null) { // 데이터가 null일 경우 공백이나 기본값으로 표시되도록 datas = new FormDto("", "", new String[]{"","","",""}, "Eclipse", "개발자", "0회", ""); } %> <!-- 3x2 테이블에 폼 요소 넣기 --> <form action="../form" method="post"> <table border=1> <tr> <th>ID </th> <td> <input type="text" id="userId" name="userId" value="<%= datas.getUserId() %>"> <input type="button" value="id체크" onclick="idCheck()"> <span id="idCheckMsg"></span> </td> </tr> <tr> <th>비밀번호 </th> <td> <input type="password" id="pw1" name="userPw" value="<%= datas.getUserPw() %>"> </td> </tr> <tr> <th>비밀번호 확인</th> <td> <input type="password" id="pw2" > <input type="button" value="비밀번호 체크" onclick="pwCheck()"> <span id="pwCheckMsg"></span> </td> </tr> <tr> <th>사용언어</th> <td> <input type="checkbox" name="lang" class="lang" onclick="checkCount()" value="0" <%= datas.getLangs()[0].equals("0") ? "checked" : "" %>>java <input type="checkbox" name="lang" class="lang" onclick="checkCount()" value="1" <%= datas.getLangs()[1].equals("1") ? "checked" : "" %>>python <input type="checkbox" name="lang" class="lang" onclick="checkCount()" value="2" <%= datas.getLangs()[2].equals("2") ? "checked" : "" %>>javascript <input type="checkbox" name="lang" class="lang" onclick="checkCount()" value="3" <%= datas.getLangs()[3].equals("3") ? "checked" : "" %>>html <span id="langCntMsg"></span> </td> </tr> <tr> <th>사용IDE</th> <td> <input type="radio" name="ide" onclick="selectedIde()" value="Eclipse" <%= datas.getIde().equals("Eclipse") ? "checked" : "" %>>Eclipse <input type="radio" name="ide" onclick="selectedIde()" value="IntelliJ" <%= datas.getIde().equals("IntelliJ") ? "checked" : "" %>>IntelliJ <input type="radio" name="ide" onclick="selectedIde()" value="Visual Studio" <%= datas.getIde().equals("Visual Studio") ? "checked" : "" %>>Visual Studio <input type="radio" name="ide" onclick="selectedIde()" value="VS Code" <%= datas.getIde().equals("VS Code") ? "checked" : "" %>>VS Code </td> </tr> <tr> <th>Role</th> <td> <select id="role" name="role"> <option>--- 역할 --- <option value="디자이너" <%= datas.getRole().equals("디자이너") ? "selected" : "" %>>디자이너 <option value="프로그래머" <%= datas.getRole().equals("프로그래머") ? "selected" : "" %>>프로그래머 <option value="설계" <%= datas.getRole().equals("설계") ? "selected" : "" %>>설계 <option value="개발자" <%= datas.getRole().equals("개발자") ? "selected" : "" %>>개발자 <option value="퍼블리셔" <%= datas.getRole().equals("퍼블리셔") ? "selected" : "" %>>퍼블리셔 </select> <input type="button" value="선택한 역할 확인" onclick="selectedRole()"> </td> </tr> <tr> <th>프로젝트 참여 횟수</th> <td> <select id="pCount" onchange="selectedPCount(this.value)" name="pCount"> <option>--- 횟수 --- <option value="0회" <%= datas.getpCount().equals("0회") ? "selected" : "" %>>0회 <option value="1회" <%= datas.getpCount().equals("1회") ? "selected" : "" %>>1회 <option value="2회" <%= datas.getpCount().equals("2회") ? "selected" : "" %>>2회 <option value="3회" <%= datas.getpCount().equals("3회") ? "selected" : "" %>>3회 <option value="4회 이상" <%= datas.getpCount().equals("4회 이상") ? "selected" : "" %>>4회 이상 </select> </td> </tr> <tr> <th>자기소개</th> <td><textarea cols="30" rows="5" name="introduce"> <%= datas.getIntroduce() %> </textarea></td> </tr> <tr> <td id="btn" colspan="2"> <input type="reset" value="새로고침"> <input type="submit" id="btn_submit" value="제출"> </td> </tr> </table> </form> </body> </html>url을 보면 제출 후에는 servlet 중심이 되어버려(controller 역할) css와 js가 풀려버림
풀리지 않게 하는 방법은 다음 게시물에서!
'웹 Web > JSP & Servlet' 카테고리의 다른 글
액션태그 - EL & Taglib (0) 2023.02.13 하나의 Servlet에서 여러 작업을 수행하기 - CRUD (0) 2023.02.08 JSP 내장 객체 (3) - Application 내장 객체 (0) 2022.01.24 JSP 내장 객체 (2) - forward (0) 2022.01.17 JSP 내장 객체 (1) - JSP로 설문조사폼(sendRedirect..) (0) 2022.01.17