λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
JSP

[JSP] forwarding

by μ½”λ”©ν•˜λŠ” λΆ•μ–΄ 2021. 2. 9.
λ°˜μ‘ν˜•

β–Ά μ„œλΈ”λ¦Ώμ—μ„œ νŠΉμ • νŽ˜μ΄μ§€λ‘œ ν¬μ›Œλ”©ν•˜λŠ” 두 가지 방법

​

1) Dispatcher 방식

μ•žμ„œ 둜그인 μ˜ˆμ œμ—μ„œ μ‚¬μš©ν•œ 방식이닀. 이 λ°©μ‹μœΌλ‘œ ν¬μ›Œλ”©μ„ ν•˜κ²Œ 되면 μ£Όμ†Œ ν‘œμ‹œμ€„μ˜ μ£Όμ†Œκ°€ λ³€κ²½λ˜μ§€ μ•ŠλŠ”λ‹€.

즉, ν•˜λ‚˜μ˜ μš”μ²­μ΄λΌλŠ” μ˜λ―Έμ΄λ‹€. λ”°λΌμ„œ 같은 request μ˜μ—­μ„ κ³΅μœ ν•˜κ²Œ λœλ‹€.

​

​

DispatcherServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	
		RequestDispatcher dispatcher = request.getRequestDispatcher("dispatcher.jsp");
		request.setAttribute("request", "requestValue");
		dispatcher.forward(request, response);
}

 

 

dispatcher.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>
    request 속성 κ°’ : <%=request.getAttribute("request") %>
</body>
</html>

μœ„μ˜ μ„œλΈ”λ¦Ώμ—μ„œλŠ” 둜그인 예제의 방식과 λ§ˆμ°¬κ°€μ§€λ‘œ dispatcher 방식에 μ˜ν•΄μ„œ ν¬μ›Œλ”©μ„ ν•˜κ²Œ λœλ‹€. dispatcher.jspμ—μ„œλŠ” request μ˜μ—­μ— requestλΌλŠ” μ΄λ¦„μœΌλ‘œ μ €μž₯λ˜μ–΄ μžˆλŠ” 값을 κ°€μ Έμ™€μ„œ 좜λ ₯ν•˜κ³  μžˆλ‹€.

 

<μ‹€ν–‰ κ²°κ³Ό>

<%=%> 뢀뢄은 λ‚΄λΆ€μ—μ„œ λ°˜ν™˜λ˜λŠ” 값을 좜λ ₯ν•˜λŠ” κΈ°λŠ₯을 ν•œλ‹€.

​

​​

​

2) Redirect 방식

ν¬μ›Œλ”©λ λ•Œ λΈŒλΌμš°μ € μ£Όμ†Œ ν‘œμ‹œμ€„ URL이 λ³€κ²½λ˜λ―€λ‘œ μš”μ²­μ΄ λ°”λ€Œκ²Œ λœλ‹€. λ”°λΌμ„œ ν¬μ›Œλ”©λœ JSP νŽ˜μ΄μ§€μ—μ„œλŠ” μ„œλΈ”

λ¦Ώμ—μ„œ request μ˜μ—­μ— κ³΅μœ ν•œ 속성 값에 μ ‘κ·Όν•  수 μ—†λ‹€.

​​

​

RedirectServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setAttribute("request", "requestValue");
		response.sendRedirect("redirect.jsp");
}

μœ„μ˜ μ½”λ“œμ—μ„œ sendRedirect(String url) λ©”μ„œλ“œκ°€ λ¦¬λ‹€μ΄λ ‰νŠΈ λ°©μ‹μœΌλ‘œ ν•΄λ‹Ή URL둜 ν¬μ›Œλ”©μ„ ν•΄μ£ΌλŠ” λ©”μ„œλ“œμ΄λ‹€.

 

 

redirect.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>
   request 속성 κ°’ : <%=request.getAttribute("request") %>
</body>
</html>

 

<μ‹€ν–‰ κ²°κ³Ό>

 

λ°˜μ‘ν˜•

λŒ“κΈ€