웹기반 애플리케이션

JSP📃_웹 어플리케이션에서 흐름 제어(A->B) 방법

비비펄 2023. 3. 9. 19:23

📕 Request Dispatche(요청 분기)
 Forward : 클라이언트->서버A->서버B->클라이언트
요청은 A(서블릿)로 응답은 B(jsp활용 케이스가 많음)에서만 처리됨.(책임의 분리구조==>Model2구조에서 활용.). 서버사이드 위임 처리 방식(A가 자기 책임을 B에게 떠넘김)

		String path ="/04/standard.jsp"; //서버가 사용하는 주소==>절대주소
		RequestDispatcher rd = request.getRequestDispatcher(path);

		//forward방식(응답형태 A=>B)
		rd.forward(request, response);
			
		//include방식(응답형태 A+B)
		rd.include(request, response);
        
        <jsp:include page="<%=path %>"/>

✔Include : 클라이언트->서버A->서버B->서버A->클라이언트(서버 B의 존재를 알 수 없음)
요청은 A로 전송 -> 서버 내에서 B로 이동-> A로 복귀
(최종 응답은 A+B의 형태로 전송, A가 B를 내포함(include).)=>페이지 모듈화에서 활용

 

📕 Redirect : 클라이언트->서버A ==>requestA ->클라이언트==>requestA사라짐
                      다시 클라이언트->서버B
  요청은 A로 전송 -> Body가 없고, 상태코드가 300번대인 응답 전송

                               (Location 헤더 포함-이동된 주소 포함) ==> connectless, stateless
                                                           -> Location(B) 방향으로 새로운 요청 전송 -> B에서 최종 응답 전송.
     301/302 : 원본 요청(A)에대한 정보가 삭제된 후, GET방식의 새로운 요청이 redirection.
      POST->Redirect->GET ==> PRG패턴 처리구조
     307 : REST 처리에서 많이 활용되며, PUT/DELETE 요청에서 활용.
      원본 요청이 발생하고, redirection 될때, 원본 요청의 method와 body를 복사해서 새로운 요청이 발생함.

<%	
	//redirect방식
	response.sendRedirect(request.getContextPath() + path); //클라이언트가 path를 사용하는 상황==>상대경로
%>

 

start.jsp

<%@ 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>
	<form action="redirectTest.jsp" method="get">
		<input type="text" name="param" value="param_value" />
		<button type="submit">전송</button>
	</form>
</body>
</html>

redirect.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%
	System.out.printf("파라미터 : %s\n", request.getParameterValues("param"));
	
	String location= request.getContextPath() + "/08/dest.jsp";
	
	//301인 경우
	response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
	 
	//302인 경우
	response.setStatus(HttpServletResponse.SC_FOUND);
	
	//307인 경우
	response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
	response.setHeader("Location", location);
%>

최종 종착지 dest.jsp

<%@ 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>
<h4>최종 도착지 (B)</h4>
<pre>
	request URI = <%=request.getRequestURI() %>
	request method = <%=request.getMethod() %>
	request parameter : <%=request.getParameter("param") %>
</pre>
</body>
</html>

 

::301인경우 결과::

::302인경우 결과:: ※301과 302는 결과가 비슷하다...

::307인경우 결과::

start.jsp 의 method방식을 post로 바꿔주면 method방식도 바뀌고 파라미터값도 들어오는 것을 볼 수 있다.