๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Java·๏ปฟServlet·๏ปฟJSP

RequestDispatcher.forward()๋ฅผ ์ด์šฉํ•œ ์—๋Ÿฌ ํŽ˜์ด์ง€ ์ถœ๋ ฅํ•˜๊ธฐ

by Leica 2020. 2. 12.
๋ฐ˜์‘ํ˜•
  • ๊ด€๋ จ ๊ธ€

- RequestDispatcher์˜ forwarding(), include()์™€ <jsp:forward>, <jsp:include> ํƒœ๊ทธ


RequestDispatcher - Fowarding VS Including

์š”์ฒญ๋œ ์ž‘์—…์„ ์œ„์ž„ํ•˜๋Š” ๋ฐฉ๋ฒ•์—๋Š” Fowarding ๋ฐฉ์‹๊ณผ Including์˜ ๋‘ ๊ฐ€์ง€ ๋ฐฉ๋ฒ•์ด ์žˆ๋‹ค. ๊ทธ ์ฐจ์ด๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

 

Fowarding : ํ•œ ๋ฒˆ ์ž‘์—…์„ ์œ„์ž„ํ•˜๋ฉด ๋‹ค์‹œ ์ด์ „ ์„œ๋ธ”๋ฆฟ์œผ๋กœ ์ œ์–ด๊ถŒ์ด ๋Œ์•„์˜ค์ง€ ์•Š๋Š”๋‹ค.

Including : ๋‹ค๋ฅธ ์„œ๋ธ”๋ฆฟ์œผ๋กœ ์ž‘์—…์„ ์œ„์ž„ํ•œ ํ›„ ๊ทธ ์„œ๋ธ”๋ฆฟ์˜ ์‹คํ–‰์ด ๋๋‚˜๋ฉด ๋‹ค์‹œ ์ด์ „ ์„œ๋ธ”๋ฆฟ์œผ๋กœ ์ œ์–ด๊ถŒ์ด ๋Œ์•„์˜จ๋‹ค.

 

Fowarding ๋ฐฉ์‹์œผ๋กœ ์—๋Ÿฌ ํŽ˜์ด์ง€ ์ถœ๋ ฅํ•˜๊ธฐ

์„œ๋ธ”๋ฆฟ์—์„œ ์œ„์™€ ๊ฐ™์ด ์˜ˆ์™ธ ์ฒ˜๋ฆฌ๋ฅผ ํ•˜๋ฉด ์˜ˆ์™ธ ๋ฐœ์ƒ ์‹œ ServletException ์ธ์Šคํ„ด์Šค๋ฅผ ํ†ฐ์บฃ ์„œ๋ฒ„๊ฐ€ ๋ฐ›๋Š”๋‹ค. (ํ†ฐ์บฃ ์„œ๋ฒ„๋กœ ๊ตฌ๋™ํ–ˆ๋‹ค๋ฉด)

 

ํ†ฐ์บฃ ์„œ๋ฒ„๊ฐ€ ์„œ๋ธ”๋ฆฟ์ด throwํ•œ ์˜ˆ์™ธ ์ธ์Šคํ„ด์Šค๋ฅผ ๋ฐ›์œผ๋ฉด ์œ„์™€ ๊ฐ™์€ ๊ฒฐ๊ณผ ํ™”๋ฉด์„ ์›น ๋ธŒ๋ผ์šฐ์ €์—๊ฒŒ ๋ณด๋‚ธ๋‹ค.

ํฌ์›Œ๋”ฉ์„ ์‚ฌ์šฉํ•ด์„œ ์˜ˆ์™ธ ๋ฐœ์ƒ ์‹œ ์œ„์™€ ๊ฐ™์ด HTTP ์˜ค๋ฅ˜ ํŽ˜์ด์ง€๋ฅผ ์ถœ๋ ฅํ•˜์ง€ ์•Š๊ณ  ์ž์ฒด์ ์ธ ์—๋Ÿฌ ํŽ˜์ด์ง€๋ฅผ ์ถœ๋ ฅํ•˜๋„๋ก ํ•  ์ˆ˜ ์žˆ๋‹ค.

 

์ถœ๋ ฅํ•  ์—๋Ÿฌ ํŽ˜์ด์ง€๋ฅผ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ž‘์„ฑํ•˜์˜€๋‹ค.

 

Error.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>์‹œ์Šคํ…œ ์˜ค๋ฅ˜</title>
</head>
<body>
์š”์ฒญ์„ ์ฒ˜๋ฆฌํ•˜๋Š” ์ค‘์— ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€์Šต๋‹ˆ๋‹ค. ์ž ์‹œ ํ›„์— ๋‹ค์‹œ ์š”์ฒญํ•˜์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค.<br>
<%
    Exception e = (Exception)request.getAttribute("error");
%>
<%=e.toString()%>
</body>
</html>
cs

 

๊ทธ๋ฆฌ๊ณ  ์˜ˆ์™ธ ์ฒ˜๋ฆฌ ๋ถ€๋ถ„์„ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋ณ€๊ฒฝํ•œ๋‹ค.

1
2
3
4
5
6
catch (SQLException | ClassNotFoundException e) {
//            throw new ServletException(e);
    req.setAttribute("error", e);
    RequestDispatcher rd = req.getRequestDispatcher("/Error.jsp");
    rd.forward(req, resp);
}
cs

 

๊ทธ๋ฆฌ๊ณ  ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•˜๋Š” ์„œ๋ธ”๋ฆฟ์„ ๋‹ค์‹œ ์‹คํ–‰ํ•˜๋ฉด Error.jsp๊ฐ€ ์ƒ์„ฑํ•œ ํ™”๋ฉด์ด ์ถœ๋ ฅ๋œ๋‹ค.

 

์‹คํ–‰ ๊ฒฐ๊ณผ


  • ๊ด€๋ จ ๊ธ€

- RequestDispatcher์˜ forwarding(), include()์™€ <jsp:forward>, <jsp:include> ํƒœ๊ทธ

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€