일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- 자바스크립트 코딩테스트
- typescript
- 자바스크립트
- 타입스크립트
- VUE
- 국비IT
- 정보처리기사요약
- 리액트
- CSS
- 정보처리기사정리
- react
- javascript
- 평일코딩
- 코딩테스트
- Oracle
- 정보처리기사실기정리
- 스프링
- 국비코딩
- 정보처리기사실기요약
- 이안의평일코딩
- 리액트네이티브
- ReactNative
- 자스코테
- 자바의정석
- php
- 정보처리기사실기
- 정보처리기사
- 오라클
- spring
- Java의정석
- Today
- Total
이안의 평일코딩
JSP 6일차 - MVC / 인터페이스 본문
2020.10.08(목)
1. MVC
M(Model) => 일반자바 => 데이터읽기, 사용자 요청 처리
Controller => 사용자 요청 => Model을 연결해서 데이터를 가지고 온다 => JSP전송 (스프링에서 지원) => JSP/Servlet
-> Servlet (화면출력(X), 연결, 보안)
View => Controller로부터 결과값을 전송 받아서 => 화면에 출력
-> JSP
톰캣
1) 서블릿 구동
2) 에러처리
URL
1) 사용자 요청
2) Controller가 사용자 요청을 받는다
3) Controller가 요청을 처리하기 위해서 Model을 찾는다 (요청처리 기능)
4) Model에서 요청처리 결과값을 Controller가 받아서
5) Controller 결과값을 request 또는 session에 담아준다
6) request => 해당 JSP로 전송
7) JSP가 구동됨과 동시에 실행된 HTML을 JSP로 전송
MVC에서 Controller 찾기 => .do
MVC구조에서는 URL주소가 반드시 .do로 끝난다
==> list.jsp ==> list.do
find.jsp ==> find.do
detail.jsp ==> detail.do
Java Resources/src/com.sist.controller
Controller.java
package com.sist.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sist.model.*;
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
// XML파싱, 파일읽기 => 생성자 역할
public void init(ServletConfig config) throws ServletException {
// ServletConfig config => 등록 web.xml에 등록 (등록된 데이터를 읽을 수 있다)
}
/*
* 사용자가 전송하는 방식(GET / POST)
* 메소드 처리가 달라진다
* GET => doGet()
* POST => doPost()
* =================
* doGet()+doPost() => service()
*
* ### Servlet => 프로그래머가 구동하는 것이 아니라 톰캣이 구동한다
* ================================================
* 톰캣이 구동 => web.xml에 등록 (스프링=>web.xml에 등록)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// /Controller?cmd=list ==> ListModel ==> list.jsp
String cmd=request.getParameter("cmd");
String jsp="";
if(cmd.equals("list")) {
ListModel model=new ListModel();
model.execute(request);
jsp="view/list.jsp";
}
else if(cmd.equals("find")) {
FindModel model=new FindModel();
model.execute(request);
jsp="view/find.jsp";
}
else if(cmd.equals("detail")) {
DetailModel model=new DetailModel();
model.execute(request);
jsp="view/detail.jsp";
}
// 해당 JSP로 request전송
RequestDispatcher rd=request.getRequestDispatcher(jsp);
rd.forward(request, response);
}
}
Java Resources/src/com.sist.model
DetailModel.java
package com.sist.model;
import javax.servlet.http.HttpServletRequest;
public class DetailModel {
public void execute(HttpServletRequest request) {
String msg="DetailModel=>list.jsp로 값을 전송";
request.setAttribute("msg", msg);
}
}
FindModel.java
package com.sist.model;
import javax.servlet.http.HttpServletRequest;
public class FindModel {
public void execute(HttpServletRequest request) {
String msg="FindModel=>list.jsp로 값을 전송";
request.setAttribute("msg", msg);
}
}
ListModel.java
package com.sist.model;
import javax.servlet.http.HttpServletRequest;
public class ListModel {
public void execute(HttpServletRequest request) {
String msg="ListModel=>list.jsp로 값을 전송";
request.setAttribute("msg", msg);
}
}
WebContent/view
detail.jsp
<%@ 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>
<center>
<h1>detail.jsp영역</h1>
<h1>${msg }</h1>
</center>
</body>
</html>
find.jsp
<%@ 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>
<center>
<h1>find.jsp영역</h1>
<h1>${msg }</h1>
</center>
</body>
</html>
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%--
ListModel model = new ListModel();
model.execute(request);
--%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
<h1>list.jsp영역</h1>
<h1>${msg }</h1>
</center>
</body>
</html>
WebContent/WEB-INF
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>OnLineStudy15_MVC</display-name>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>com.sist.controller.Controller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/Controller</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
===========================================================
2. 인터페이스 (스프링의 기본구조)
클래스 여러개를 모아서 한번에 관리
Java Resources/src/com.sist.controller
Controller.java
package com.sist.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import com.sist.model.*;
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
//////////////////////////////////////////////////
//// DeleteModel ==> delete.jsp
String[] strCmd={
"list",
"detail",
"insert",
"update",
"delete"
};
String[] strClass={
"com.sist.model.ListModel",
"com.sist.model.DetailModel",
"com.sist.model.InsertModel",
"com.sist.model.UpdateModel",
"com.sist.model.DeleteModel"
};
////////////////////////////////////////////////// XML
// <bean id="list" class="com.sist.model.ListModel">
private Map clsMap=new HashMap();
public void init(ServletConfig config) throws ServletException {
try
{
for(int i=0;i<strClass.length;i++)
{
Class cls=Class.forName(strClass[i]);
Object obj=cls.newInstance();// 메모리 할당 (리플렉션)
// 클래스명을 받아서 메모리 할당 => 모든 정보를 제어(메소드,생성자,멤버변수 제어)
System.out.println(strCmd[i]+":"+obj);
clsMap.put(strCmd[i], obj);
}
}catch(Exception ex){}
}
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 사용자의 요청처리
/*
* http://localhost/OnLineStudy15_MVC2/*.do
*
* * ==> 어떤 단어를 사용해도 된다
* *.do
* list.do
* detail.do ==> Controller를 호출하고 있다
* ====== 키로 이용
*/
// http://localhost/OnLineStudy15_MVC2/list.do
String cmd=request.getRequestURI();
// /OnLineStudy15_MVC2/list.do ==> getRequestURI()
System.out.println("cmd:"+cmd);
cmd=cmd.substring(request.getContextPath().length()+1,cmd.lastIndexOf("."));
// /OnLineStudy15_MVC2 ==> request.getContextPath()
// /OnLineStudy15_MVC2/ list .do
System.out.println("cmd2:"+cmd);
// 클래스 찾는다
Model model=(Model)clsMap.get(cmd);
// 메소드를 호출해서 ==> 기능(요청) 처리
String jsp=model.execute(request);
// request에 값을 담아서 => JSP로 전송
RequestDispatcher rd=request.getRequestDispatcher(jsp);
rd.forward(request, response);
}
}
Java Resources/src/com.sist.model
Model.java
package com.sist.model;
import javax.servlet.http.HttpServletRequest;
/*
* 클래스의 유형이 다르면 조건문
* 모든 클래스 유형이 동일 ==> interface
*
* class A
* class B
*
* interface I
* class A implements I
* class B implements I
*
* I i=new A()
* I i=new B()
*
* 클래스 여러개를 모아서 한번에 관리 => 인터페이스 (스프링의 기본구조)
*
*
*/
public interface Model {
public String execute(HttpServletRequest request);
}
DeleteModel.java
package com.sist.model;
import javax.servlet.http.HttpServletRequest;
public class DeleteModel implements Model {
@Override
public String execute(HttpServletRequest request) {
// TODO Auto-generated method stub
request.setAttribute("msg", "삭제하기");
return "board/delete.jsp";
}
}
DetailModel.java
package com.sist.model;
import javax.servlet.http.HttpServletRequest;
public class DetailModel implements Model {
@Override
public String execute(HttpServletRequest request) {
// TODO Auto-generated method stub
request.setAttribute("msg", "내용보기");
return "board/detail.jsp";
}
}
InsertModel.java
package com.sist.model;
import javax.servlet.http.HttpServletRequest;
public class InsertModel implements Model {
@Override
public String execute(HttpServletRequest request) {
// TODO Auto-generated method stub
request.setAttribute("msg", "글쓰기");
return "board/insert.jsp";
}
}
ListModel.java
package com.sist.model;
import javax.servlet.http.HttpServletRequest;
public class ListModel implements Model {
@Override
public String execute(HttpServletRequest request) {
// TODO Auto-generated method stub
request.setAttribute("msg", "게시판 목록");
return "board/list.jsp";
}
}
UpdateModel.java
package com.sist.model;
import javax.servlet.http.HttpServletRequest;
public class UpdateModel implements Model {
@Override
public String execute(HttpServletRequest request) {
// TODO Auto-generated method stub
request.setAttribute("msg", "수정하기");
return "board/update.jsp";
}
}
WebContent
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>OnLineStudy15_MVC2</display-name>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>com.sist.controller.Controller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
WebContent/board
detail.jsp
<%@ 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>
<center>
<h1>${msg }</h1>
</center>
</body>
</html>
insert.jsp
<%@ 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>
<center>
<h1>${msg }</h1>
</center>
</body>
</html>
list.jsp
<%@ 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>
<center>
<h1>${msg }</h1>
</center>
</body>
</html>
update.jsp
<%@ 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>
<center>
<h1>${msg }</h1>
</center>
</body>
</html>
===========================================================================
Java Resources/src/com.sist.controller
Controller.java
package com.sist.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// XML => Annotation
import java.util.*;
import com.sist.model.*;
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
/*
* 매칭 ==> ListModel == list.jsp (list.jsp)
* DetailModel == detail.jsp (detail.jsp)
* 요청처리 (Model)
* 클라이언트 ========> Controller ====>==> Model <====> DAO
* 요청 (request) (request) 결과값을 request에 담는다
* | <======
* | request
* |
* JSP request.setAttribute()
* => request.getAttribute() ==> ${}
* JSP ==> Controller => Model => Controller => JSP
* 요청 요청처리 결과값 출력
*/
// 1. 클라이언트가 Controller 요청을 하면 ==> 요청을 처리하는 Model클래스 찾기
// Controller가 어떤 요청인지 알 수가 없다 => 인식
// list ==> ListModel
// detail ==> DetailModel
private Map clsMap=new HashMap();
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1. 요청을 받는다 ==> list, detail
// 2. http://localhost/OnLineStudy15_MVC/(list).do
// 3. http://localhost/OnLineStudy15_MVC/(detail).do
// 4. http://localhost/OnLineStudy15_MVC/Controller?cmd=list
String cmd=request.getRequestURI(); // OnLineStudy15_MVC/(list).do
// URI ==> /OnLineStudy15_MVC/(list).do(?page=2) => request에 따로 설정
System.out.println(cmd);
cmd=cmd.substring(request.getContextPath().length()+1,cmd.lastIndexOf("."));
// request.getContextPath()+1:/OnLineStudy15_MVC/
// 사용자가 요청한 요청내용 확인
// 클래스를 찾기 시작
Model model=(Model)clsMap.get(cmd);
// 요청처리 => 메소드
String jsp=model.handlerRequest(request);
// 결과값을 받은 request ==> jsp로 전송
RequestDispatcher rd=request.getRequestDispatcher(jsp);
rd.forward(request, response);
// 18장에 나오는 코드
}
@Override
public void init(ServletConfig config) throws ServletException {
clsMap.put("list", new ListModel());
clsMap.put("detail", new DetailModel()); // 싱글턴
}
}
Java Resources/src/com.sist.model
Model.java
package com.sist.model;
import javax.servlet.http.HttpServletRequest;
/*
* execute() ==> Struts
* handlerRequest() ==> Spring
*/
public interface Model {
public String handlerRequest(HttpServletRequest request);
}
DetailModel.java
package com.sist.model;
import javax.servlet.http.HttpServletRequest;
/*
* class A ==> A 데이터형
* {
* }
* class B ==> B 데이터형
* {
* }
*
* interface I ==> I 데이터형
* {
* }
*
*
* class A implements I ==> A,I
* A a=new A();
* I i=new A();
*
* class 동물
* class 사람 extends 동물
*
* 관련된 여러개 클래스를 통합 ==> 인터페이스 (리모콘)
*
*/
public class DetailModel implements Model {
@Override
public String handlerRequest(HttpServletRequest request) {
// TODO Auto-generated method stub
return null;
}
}
ListModel.java
package com.sist.model;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
public class ListModel implements Model{
@Override
public String handlerRequest(HttpServletRequest request) {
List<String> list=new ArrayList<String>();
list.add("홍길동");
list.add("심청이");
list.add("박문수");
list.add("이순신");
list.add("춘향이");
request.setAttribute("list", list);
return "board/list.jsp";
}
}
WebContent/board
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
<h1>이름 목록</h1>
<c:forEach var="name" items="${list }">
${name }<br>
</c:forEach>
</center>
</body>
</html>
WebContent/WEB-INF
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>OnLineStudy15_MVC3</display-name>
<!-- Servlet 등록 -->
<!--
map.put("mvc",com.sist.controller.Controller)
==> map.get("mvc")
-->
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>com.sist.controller.Controller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
'Back-end > JSP' 카테고리의 다른 글
JSP 8일차 - Annotation (0) | 2020.10.13 |
---|---|
JSP 7일차 - Interface, 자유게시판 (0) | 2020.10.12 |
JSP 5일차 - JSTL / 망고플레이트 (0) | 2020.10.07 |
JSP 4일차 - Express Language, JSTL / 게시판 (2) | 2020.10.05 |
JSP 3일차 - include (0) | 2020.09.22 |