본문 바로가기
Servlet

[JSP/Servlet] request.getRequestDispatcher 사용해 java 파일로 forward 하는 방법과 <jsp:forward page=""> 사용해 jsp 파일로 forward 하는 방법

by happyhelen 2022. 3. 9.

 

  • 예시를 최대한 간단하게 보기 위해 style 과 유효성 검사는 생략했다. 
  • 흐름을 이해하면서 데이터를 어떻게 전송하고 꺼내보는지에 주목해서 복습하는 용도이다.
  • 두 가지 예시가 나온다.

 

 

1-1) 아래는 성명, 학력, 색상, 음식을 입력 및 선택해서 제출하는 화면이다.

form 태그의 action 은 "<%= ctxPath%>/registerPerson.do" 이고, 전송 버튼을 누르면 type="submit" 이 작동한다.

또한, jQuery 로 유효성 검사를 했다.

action 이 .do 로 끝나는 걸 보면 java 파일로 이동한다는 것을 예상할 수 있다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>    
<%
	String ctxPath = request.getContextPath();
%>        
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Post 방식으로 데이터 전송하기</title>
	<style --- 생략 --->
<script type="text/javascript" src="<%=ctxPath %>/js/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
	$(document).ready(function(){		
		// === 유효성 검사 === //	
		$("form[name='memberFrm']").submit(() => {
			--- 생략 ---
		});
	});
</script>
</head>
<body>
	<form name="memberFrm" action="<%= ctxPath%>/registerPerson.do" method="post">
        <fieldset>
        <legend>개인성향 테스트(POST method)</legend>
        <ul>
          <li><label for="name">성명</label> 
              <input type="text" name="name" id="name" placeholder="성명입력" />
          </li>
          <li><label for="school">학력</label> 
              <select name="school" id="school">
                  <option value="">학력선택</option>
                  <option>고졸</option>
                  <option>초대졸</option>
                  <option>대졸</option>
                  <option>대학원졸</option>
              </select>
          </li>
          <li><label for="">좋아하는 색상</label>
              <div>
                  <label for="red">빨강</label> 
                  <input type="radio" name="color" id="red" value="red" /> 

                  <label for="blue">파랑</label> 
                  <input type="radio" name="color" id="blue" value="blue" /> 

                  <label for="green">초록</label> 
                  <input type="radio" name="color" id="green" value="green" /> 

                  <label for="yellow">노랑</label> 
                  <input type="radio" name="color" id="yellow" value="yellow" />
              </div>
          </li>
          <li><label for="">좋아하는 음식(다중선택)</label>
              <div>
                  <label for="food1">짜짱면</label> 
                  <input type="checkbox" name="food" id="food1" value="짜짱면" /> &nbsp; 

                  <label for="food2">짬뽕</label> 
                  <input type="checkbox" name="food" id="food2" value="짬뽕" /> &nbsp; 

                  <label for="food3">탕수육</label> 
                  <input type="checkbox" name="food" id="food3" value="탕수육" /> &nbsp; 

                  <label for="food4">양장피</label>
                  <input type="checkbox" name="food" id="food4" value="양장피" /> &nbsp; 

                  <label for="food5">팔보채</label> 
                  <input type="checkbox" name="food" id="food5" value="팔보채" />
              </div>
          </li>
          <li>
              <input type="submit" value="전송" /> 
              <input type="reset" value="취소" />
          </li>
        </ul>
	  </fieldset>
	</form>
</body>
</html>

 

 

1-2) 아래는 java 파일이다.

@WebServlet 어노테이션으로 서블릿을 명시했다.

여기서는 제대로 post 방식으로 데이터가 들어왔다면,

.getParameter("name값") 으로 위에서 넘어온 데이터를 가져와

 request.setAttribute("paraMap", paraMap); 로 request 영역에 데이터를 저장해주고, 

이어서 request.getRequestDispatcher 로 forward 해줄 파일을 명시 및 dispatcher.forward 를 해준다.

하지만 잘못된 방식으로 데이터가 들어왔다면, error 파일로 forward 를 해준다.

 

package chap03;
import 생략;

@WebServlet("/registerPerson.do")
public class RegisterPerson extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String method = request.getMethod();
       
		if("POST".equalsIgnoreCase(method)) {// POST 방식으로 들어온 경우
			String name = request.getParameter("name");
			String school = request.getParameter("school");
			String color = request.getParameter("color");
            
			String[] foodArr = request.getParameterValues("food");
			String foods = String.join(",", foodArr);

			// 여러개일 경우 아래처럼 모아서 setAttribute 한다.
			Map<String, String> paraMap = new HashMap<>();
			paraMap.put("name",name);
			paraMap.put("school",school);
			paraMap.put("color",color);
			paraMap.put("foods",foods);
			
			request.setAttribute("paraMap", paraMap);
			RequestDispatcher dispatcher = request.getRequestDispatcher("/chap03_StandardAction/04_forwardForm_view_02.jsp");
			dispatcher.forward(request, response);
			
		}else {// 허락되지 않은 GET 방식으로 들어온 경우
			// forward 로 에러페이지로 넘겨준다.
			RequestDispatcher dispatcher = request.getRequestDispatcher("/chap03_StandardAction/04_forwardForm_error_03.jsp");
			dispatcher.forward(request, response);
		}
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

 

1-3) 테스트 결과를 보여주는 view 단이다. jsp 파일이다.

위에서 Map 으로 데이터를 보냈기 때문에 여기서도 Map 으로 캐스팅해서 getAtrribute 를 한다.

스크립틀릿으로는 map.get("키") 로 데이터를 꺼내고, EL 로는 requestScope.paraMap.키 로 데이터를 꺼낸다.

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.Map" %>
<%
	Map<String, String> map = (Map<String, String>)request.getAttribute("paraMap");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>개인 성향 테스트 결과화면</title>
</head>
<body>
	<h2>개인 성향 테스트 결과</h2>
	
	<h3>스크립틀릿을 사용한 것</h3>
	<span style="color: blue;"><%= map.get("name")%></span>님의 개인 성향은 <br/><br/>
	학력은 <%= map.get("school")%>이며, <%= map.get("color")%>색을 좋아합니다. <br/>
	좋아하는 음식은 <%= map.get("foods")%>입니다. <br/>
	<hr style="border: solid 1px red;">
    
	<h3>EL을 사용한 것</h3>
    
	<span style="color: purple;">${requestScope.paraMap.name}</span> 님의 개인 성향은 <br/><br/>
	학력은 ${requestScope.paraMap.school}이며, ${requestScope.paraMap.color} 색을 좋아합니다. <br/>
	좋아하는 음식은 ${requestScope.paraMap.foods} 입니다. <br/>
</body>
</html>

 

 

 

2-1) 아래는 두 수를 입력하는 화면이다. ( 후에 두 수 사이의 수들을 누적한다. )

계산하기 버튼을 누르면 goSubmit() 함수가 작동되어 유효성 검사가 진행되고, 유효성 검사가 통과하면 

action="03forwardCalc_EL_02.jsp" 로 submit() 된다.

또한 정규표현식으로 유효성 검사를 했다. 

action 이 .jsp 로 끝나는 걸 보면 jsp 파일로 이동한다는 것을 예상할 수 있다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSP 표준액션 중 forward 에 대해 알아보자</title>
</head>
<body>
	<h2>입력한 두 수 사이를 누적한 값 알아오기(EL 사용한 예제)</h2>

	<form name="myFrm">
	  <p>
	         첫번째 수 : <input type="text" name="firstNum" size="5" maxlength="5" /><br/>
	         두번째 수 : <input type="text" name="secondNum" size="5" maxlength="5" /><br/>
	     <button type="button" onclick="goSubmit()">계산하기</button> 
     	  </p>
	</form>
	
	<script type="text/javascript">
		// Function declaration
		function goSubmit() {
			// 정규표현식으로 유효성검사
			--- 생략 ---
            
            		frm.action = "03forwardCalc_EL_02.jsp";
			// frm.method = "get"; // method 를 명시하지 않으면 기본값은 "get" 이다.
			frm.submit();
			
		}// end of function goSubmit()----------------------------
	
	</script>
</body>
</html>

 

 

2-2) 아래는 jsp 파일이다.

.getParameter("name값") 으로 위에서 넘어온 데이터값을 가져와서 계산을 해주고

 request.setAttribute("키",값) 으로 request 영역에 저장한다.

그리고 jsp 에서는 java 와 달리 action 으로 <jsp:forward page="03forwardCalc_EL_view_03.jsp"/> 처럼 forward 를 진행한다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String s_firstNum = request.getParameter("firstNum");
	String s_secondNum = request.getParameter("secondNum");
	
	int firstNum = Integer.parseInt(s_firstNum);
	int secondNum = Integer.parseInt(s_secondNum);
	
	int sum = 0;
	for(int i=firstNum; i<=secondNum; i++){
		sum += i;
	}
	
	// 결과물은 sum 이다.
	System.out.println("sum => " + sum);

 	 request.setAttribute("firstno", firstNum); 
 	 request.setAttribute("secondno", secondNum);
 	 
 	 request.setAttribute("hab", sum);
 	 
%>

<jsp:forward page="03forwardCalc_EL_view_03.jsp"/>

 

2-3) 테스트 결과를 보여주는 view 단이다. jsp 파일이다.

EL 로 작성되었기 때문에 requestScope.키 로 데이터를 꺼내왔는데, requestScope 는 생략이 가능하다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>계산된 결과값을 보여주는 곳</title>
</head>
<body>
	<h3>계산된 결과값(EL 사용한 것) -3</h3>
	${requestScope.firstno}부터 ${requestScope.secondno}까지의 합은? <br> 
	결과값 : <span style="color:green;">${requestScope.hab}</span>
	
	<br><br>
	
	<h3>계산된 결과값(EL 사용한 것, requestScope. 생략가능) -4</h3>
	${firstno}부터 ${secondno}까지의 합은? <br> 
	결과값 : <span style="color:purple;">${hab}</span>
</body>
</html>