forward
getRequestDispatcher("");
RequestDispatcher dispatcher = request.getRequestDispatcher("spaghetti.jsp");
dispatcher.forward(request, response);
스파게티 코드
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String num_ = request.getParameter("n");
int num = 0;
if(num_ != null && !num_.equals("")) {
num = Integer.parseInt(num_);
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%if(num % 2 == 0) { %>
짝수입니다.
<% } else { %>
홀수입니다.
<% } %>
</body>
</html>
컨트롤러와 뷰가 물리적으로 분리되지 않은 방식
Model
: 출력 데이터 View
: 출력 담당 [HTML 코드]
Cotroller
: 입력과 제어를 담당 [JAVA 코드]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String num_ = request.getParameter("n");
int num = 0;
if(num_ != null && !num_.equals("")) {
num = Integer.parseInt(num_);
}
String result;
if(num % 2 == 0) {
result = "짝수";
}else {
result = "홀수";
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%= result %> 입니다.
</body>
</html>
컨트롤러와 뷰가 물리적으로 분리된 방식
package com.web;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/spaghetti")
public class spaghetti extends HttpServlet{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String num_ = request.getParameter("n");
int num = 0;
if(num_ != null && !num_.equals("")) {
num = Integer.parseInt(num_);
}
String result;
if(num % 2 == 0) {
result = "짝수";
}else {
result = "홀수";
}
request.setAttribute("result", result);
RequestDispatcher dispatcher = request.getRequestDispatcher("spaghetti.jsp");
dispatcher.forward(request, response);
RequestDispatcher dispatcher = request.getRequestDispacter("경로");
dispatcher.forward(request, response);
}
}
<%@ 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.getAttribute("result") %> 입니다.
</body>
</html>
forward
getRequestDispatcher("");
RequestDispatcher dispatcher = request.getRequestDispatcher("spaghetti.jsp");
dispatcher.forward(request, response);
Servlet / JSP