jsp_MVC패턴
MVC란?
M : Model
사용자가 원하는 데이터나 정보를 제공한다.
애플리케이션의 정보, 데이터를 나타내며 이러한 Data와 정보들의 가공을 책임지는 역할을 한다.
Model안에서 DB를 호출한다.
V : View
보여지는 화면이다.
input의 텍스트, 체크박스 항목 등과 같은 사용자 인터페이스 요소를 나타낸다. 다시말해 데이터 및 객체의 입력, 그리고 보여주는 출력을 담당한다. 데이터를 기반으로 사용자들이 볼 수 있는 화면이다.
C : Controller
사용자의 요청을 처리하고, 그 요청에 따른 전체적인 흐름을 제어한다.
데이터와 사용자의 인터페이스 요소들을 잇는 다리역할을 한다.
즉, MVC는 각각의 역할을 명확하게 쪼개두는 것이다.
이는 역할분담과 문제해결을 간단하게 할 수있다는 장점이 있어 모든 웹개발은 MVC로 의도적으로 패턴화 시켜 진행한다.
MVC 1패턴
MVC1 패턴의 경우 View와 Controller를 모두 JSP가 담당하는 형태를 가진다. 즉, JSP 하나로 유저의 요청을 받고 응답을 처리하므로 구현 난의도는 쉽다.
난의도가 쉽기때문에 아주 간단한 업무 처리를 하는 웹페이지에 적합하나, 내용이 복잡하고 거대해질 수록 이 패턴은 힘을 잃는다. 즉, 유지보수에 있어서 문제가 발생한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%
int num = 0;
String num_ = request.getParameter("num");
if(num_ != null && !num_.equals("")){
num = Integer.parseInt(num_);
}
%>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<% if(num%2 != 0){ %>
홀수입니다.
<% } else{ %>
짝수입니다.
<% } %>
</body>
</html>
|
cs |
위의 코드는 아주 단순한 넘어온 파라미터의 값에 따라서 홀수인지 짝수인지를 나타내는 코드이다.
이 코드에 MVC1 패턴을 넘겨보면
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%
int num = 0;
String num_ = request.getParameter("num");
if(num_ != null && !num_.equals("")){
num = Integer.parseInt(num_);
}
String result = "";
if(num%2 != 0){
result = "홀수";
} else{
result="짝수";
}
%>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%= result %> 입니다.
</body>
</html>
|
cs |
위와 같은 코드가 완성된다.
JAVA단을 위로 올려 모아버리고 body단의 코드를 간결하게 하였다.
4행~16행까지가 Controller 영역이고
19행~28행까지 데이터가 보여지는 영역 View 영역이며
25행이 Model영역이라고 생각한다.
MVC 2패턴
MVC 패턴은 널리 표준으로 사용되는 패턴이다. 요청을 하나의 컨트롤러가 먼저 받는다.
즉, MVC1과는 다르게 Controller, View가 분리되어 있다. 그러므로 개발자는 M,V,C 중에서 수정해야할 부분이 있다면, 그것만 꺼내서 수정하면 된다. 따라서 유지보수에 있어서 큰 이점을 가진다.
*Caos.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
package com.koreait.web.servlet;
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("/caos")
public class Caos extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
int num = 0;
String num_ = req.getParameter("num");
if(num_ != null && !num_.equals("")){
num = Integer.parseInt(num_);
}
String result = "";
if(num%2 != 0){
result = "홀수";
} else{
result="짝수";
}
//java의 페이지전달
req.setAttribute("result", result);
//RequestDispatcher: 요청을 제공하는 도구 즉, 요청을 보내주는 인터페이스
RequestDispatcher dispatcher
= req.getRequestDispatcher("/mvc/caos_mvc2.jsp");
dispatcher.forward(req, resp);
}
}
|
cs |
*Caos_mvc2.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<!--
int num = 0;
String num_ = request.getParameter("num");
if(num_ != null && !num_.equals("")){
num = Integer.parseInt(num_);
}
String result = "";
if(num%2 != 0){
result = "홀수";
} else{
result="짝수";
}
%> -->
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%= request.getAttribute("result") %> 입니다.
</body>
</html>
|
cs |
Caos.java가 Controller 역할
caos_mvc2_jsp의 25행이 Model 역할
caos_mvc2_jsp의 19행~28행이 View 역할
즉, jsp파일에서 controller를 java파일로 분리를 하는 것이 MVC2 패턴이다.
MVC1 패턴을 활용한 예시(회원가입)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
<%@ 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>
<h3> 회원가입 </h3>
<form action="join.jsp" id="joinForm" method="post">
아이디 <input type="text" name="userid" id="userid"><br>
비밀번호 <input type="text" name="userpw" id="userpw"><br>
이름 <input type="text" name="username" id="username"><br>
핸드폰 번호 <input type="text" name="userphone" id="userphone"><br>
<br>
<input type="button" value="회원가입" onclick="sendit()" />
</form>
<script>
function sendit(){
let frm = document.getElementById("joinForm");
let idTag= document.getElementById("userid");
let pwTag= document.getElementById("userpw");
let nameTag = frm.username;
let phoneTag = frm.userphone;
if(idTag.value=""){
alert("아이디를 입력하세요!");
idTag.focus();
return false;
}
if(pwTag.value=""){
alert("비밀번호를 입력하세요!");
pwTag.focus();
return false;
}
if(pwTag.value.length < 8){
alert("비밀번호를 8자리이상 입력하세요!");
pwTag.focus();
return false;
}
if(nameTag.value=""){
alert("이름을 입력하세요!");
nameTag.focus();
return false;
}
if(phoneTag.value=""){
alert(" 휴대폰 번호를 입력하세요!");
phoneTag.focus();
return false;
}
frm.submit();
} </script>
</body>
</html>
|
cs |
원래 submit이 전송을 하는 역할인데 여기서 button으로 바꿔주어 frm에 담아주었고 이를 frm.submit()으로 호출하여 MVC1 패턴으로 출력해주었다.
MVC2 패턴을 활용한 예시(회원가입)
*UserBean(java처리)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
package com.koreait.beans;
public class UserBean {
private String userid;
private String userpw;
private String username;
private String userphone;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getUserpw() {
return userpw;
}
public void setUserpw(String userpw) {
this.userpw = userpw;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserphone() {
return userphone;
}
public void setUserphone(String userphone) {
this.userphone = userphone;
}
}
|
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
package com.koreait.dao;
import com.koreait.beans.UserBean;
public class UserDao {
//DB CONNECTION
//회원가입
public boolean join(UserBean bean) {
//DB처리
//..
return true;
}
}
|
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
<%@page import="com.koreait.beans.UserBean"%>
<%@page import="com.koreait.dao.UserDao"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%
String userid = request.getParameter("userid");
String userpw = request.getParameter("userpw");
String username = request.getParameter("username");
String userphone = request.getParameter("userphone");
UserDao udao = new UserDao();
UserBean bean = new UserBean();
bean.setUserid(userid);
bean.setUserpw(userpw);
bean.setUsername(username);
bean.setUserphone(userphone);
boolean check = udao.join(bean);
if(check){ //true
//가입성공
}else{
//가입실패
}
%>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
</body>
</html>
|
cs |