๐ฌ ์ฝ๋ >>
โ index.jsp
<form id="form1" action="/chap03/forwardtest" method="POST"></form>
<input type="text" name="type" value="drink" form="form1"/>
<input type="text" name="name" value="Americano" form="form1"/>
<input type="text" name="price" value="7000" form="form1"/>
<input type="text" name="qty" value="5" form="form1"/>
<input type="submit" value="๋ณด๋ด๊ธฐ" form="form1"/>
โ java(servlet)ํ์ผ
@WebServlet("/forwardtest")
public class ForwardServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// ์๋ฐ๋ฅผ ์ฌ์ฉํด ์๋ฐ๋ก ์ฒ๋ฆฌํ๊ณ ์ถ์ ๋ด์ฉ๋ค์ ์ฒ๋ฆฌํ๋ค ...
String type = req.getParameter("type");
String name = req.getParameter("name");
String price = req.getParameter("price");
String qty = req.getParameter("qty");
int total_price = 0;
// String์ผ๋ก ๋ฐ์ ๋ฐ์ดํฐ๋ฅผ ํ์ฉํ ๋ null์ด ๋ค์ด์์ ๊ฒ์ ๋๋นํด์ผ ํ๋ค
if(price!=null && qty !=null) { // ๋๋ค null์ด ์๋๋ ๋ง parseint
System.out.printf("%s(%s) / %d\n",name, type,
total_price = (Integer.parseInt(price)*Integer.parseInt(qty)));
}else {
System.out.printf("%s(%s) / undefined\n", name, type);
}
//3.
// ์ฒ๋ฆฌ ํ ์ป์ด๋ธ ๊ฒฐ๊ณผ๋ฅผ ๋ค์ ์๋ธ๋ฆฟ๊น์ง ์ ๋ฌํ๊ณ ์ถ์ ๋๋
// request๊ฐ์ฒด์ ๋ฐ์ดํฐ๋ฅผ ์ค์ด ๋ณด๋ผ ์ ์๋ค (attribute)
req.setAttribute("full_name", String.format("%s(%s)", name, type));
req.setAttribute("total_price", total_price);
//2.
// ์์ฒญ์ ๋ค๋ฅธ๊ณณ์ผ๋ก ๋๊ธฐ๊ธฐ ์ํ ๊ธฐ๋ฅ๋ค์ด ๋ค์ด์๋ ๊ฐ์ฒด
// forward : ์์ฒญ ๊ฐ์ฒด๋ฅผ ๋ค๋ฅธ๊ณณ์ผ๋ก ๋๊ฒจ ์ฒ๋ฆฌํ ํ ๊ทธ๊ณณ์์ ์๋ตํ๋ค
// include : ์์ฒญ ๊ฐ์ฒด๋ฅผ ๋ค๋ฅธ๊ณณ์ผ๋ก ๋๊ฒจ ์ฒ๋ฆฌํ ํ ๋ค์ ๋์์จ๋ค
RequestDispatcher dispatcher = req.getRequestDispatcher("/forward/view.jsp");
dispatcher.forward(req, resp);
}
}
โ view.jsp (๋น์ฆ๋์ค ๋ก์ง ์ฒ๋ฆฌ๊ฐ ๋ชจ๋ ๋๋ ํ ์ฌ์ฉ์์๊ฒ ๋ณด์ฌ์ง๋ ํ์ด์ง/view)
<h3># ์ด์ ์๋ธ๋ฆฟ์ผ๋ก๋ถํฐ ๋๊ฒจ๋ฐ์ ๋ฐ์ดํฐ๋ค</h3>
ํ ๋ค์ : <%=request.getAttribute("full_name") %><br>
์ด ๊ฐ๊ฒฉ : <%=request.getAttribute("total_price") %><br>
๐บ ํ๋ฉด ์ถ๋ ฅ >>
๐ฌ ์ฝ๋ >>
โ index.jsp
<form id="form2" action="/chap03/redirect_test" method="POST">
</form>
<input type="text" name="type" value="drink" form="form2"/>
<input type="text" name="name" value="Americano" form="form2"/>
<input type="text" name="price" value="7000" form="form2"/>
<input type="text" name="qty" value="5" form="form2"/>
<input type="submit" value="๋ณด๋ด๊ธฐ" form="form2"/>
โ java(servlet)ํ์ผ
@WebServlet("/redirect_test")
public class RedirectServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect("/chap03/forward/view.jsp");
}
}