MVC란?
Model2 방식 중에서 가장 많이 사용하는 방식
Model-View-Controller의 약자
화면 처리, 비즈니스 로직 처리, 요청 처리를 분리하여 프로그램을 개발하는 디자인 패턴
Model2
비즈니스 로직과 화면 처리를 Java와 Jsp로 분리하여 처리하는 웹 애플리케이션 모델
각 기능이 모듈화되어 처리됨
디자이너는 화면 기능을 구현하고, 개발자는 비즈니스 로직을 구현하기 때문에 업무 분할이 가능해짐
개발 및 유지보수가 쉽고, 코드 재사용이 가능함
JSP와 서블릿을 사용하여 현재 날짜와 현재 시간을 표시하는 기본적인 기능을 구현
JSP (index.jsp)
사용자가 "현재 날짜" 또는 "현재 시간"을 선택할 수 있는 드롭다운 목록(select)과 "요청" 버튼이 있는 폼을 포함합니다.
jQuery를 사용하여 버튼 클릭 이벤트를 처리하고,
사용자가 선택한 옵션에 따라 form의 action 속성을 동적으로 변경합니다.
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
|
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<script>
$(function(){
$('#btn_submit').click(function(){
if($('#type').val() === '1'){
$('#frm').attr('action', '${contextPath}/getDate.do');
} else if($('#type').val() === '2'){
$('#frm').attr('action', '${contextPath}/getTime.do');
}
})
})
</script>
</head>
<body>
<div>
<form id="frm" method="get">
<select id="type">
<option value="1">현재날짜</option>
<option value="2">현재시간</option>
</select>
<button id="btn_submit" type="submit">요청</button>
</form>
</div>
</body>
</html>
|
cs |
서블릿 (MvcController.java):
doGet 메서드에서 요청 URL을 분석하여 사용자 요청에 맞는 서비스 메서드를 호출합니다.
MvcService를 구현한 MvcServiceImpl 객체를 생성하고, 요청에 따라 getDate 또는 getTime 메서드를 호출합니다.
각 메서드는 현재 날짜 또는 시간을 계산하여 JSP로 전달하고, JSP 페이지로 포워딩합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String requestURI = request.getRequestURI(); /* /mvc/getDate.do */
String contextPath = request.getContextPath(); /* /mvc */
String urlMapping = requestURI.substring(contextPath.length()); /* /getDate.do */
MvcService mvcService = new MvcServiceImpl();
String path = null;
switch(urlMapping) {
case "/getDate.do":
path = mvcService.getDate(request);
break;
case "/getTime.do":
path = mvcService.getTime(request);
break;
}
request.getRequestDispatcher(path).forward(request, response);
}
|
cs |
서비스 (MvcService.java, MvcServiceImpl.java):
MvcService 인터페이스는 서비스 계층의 메서드를 정의합니다. getDate 및 getTime 메서드가 포함되어 있습니다.
MvcServiceImpl 클래스는 MvcService 인터페이스를 구현하며, 현재 날짜와 현재 시간을 계산하고, 요청 객체에 해당 정보를 설정한 다음 "views/result.jsp" 페이지로 포워딩합니다.
interface
1
2
3
4
5
6
7
8
|
package service;
import javax.servlet.http.HttpServletRequest;
public interface MvcService {
public String getDate(HttpServletRequest request);
public String getTime(HttpServletRequest request);
}
|
cs |
구현
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
package service;
import java.time.LocalDate;
import java.time.LocalTime;
import javax.servlet.http.HttpServletRequest;
public class MvcServiceImpl implements MvcService {
@Override
public String getDate(HttpServletRequest request) {
request.setAttribute("today", LocalDate.now().toString());
return "views/result.jsp";
}
@Override
public String getTime(HttpServletRequest request) {
request.setAttribute("now", LocalTime.now().toString());
return "views/result.jsp";
}
}
|
cs |
JSP 결과 표시 (result.jsp):
JSP에서는 서블릿으로부터 전달받은 현재 날짜(today)와 현재 시간(now) 정보를 출력합니다.
${today}와 ${now}는 서블릿에서 설정한 속성 값에 해당합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
</head>
<body>
<c:if test="${today != null}">
${today}
</c:if>
<c:if test="${now != null}">
${now}
</c:if>
</body>
</html>
|
cs |
주의사항
실행할때 폴더 자체를 실행시켜야함!!!
'코딩기록 저장소 🐕 > JSP' 카테고리의 다른 글
DBCP (0) | 2023.09.19 |
---|---|
mvc pattern2 (0) | 2023.09.19 |
jsp session 로그인 장바구니 cookie (0) | 2023.09.18 |
JSP jstl (0) | 2023.09.15 |
JSP Lombok (0) | 2023.09.15 |