모델2
액션클레스 <= 인터페이스 다수의 액션클래스 동일한형태
자료형일치
형태통일화
servlet : BasicController
클래스핸들러 : HelloHandler
인터페이스 : CommandHandler
뷰 : hello.jsp
맵핑 : web.xml
properties 설정파일 : commandHandler.properties
hello = HelloHandler
list = ListHandler
Notice = NoticeHandler
1.클라이언트 요청 : /basic?command=hello
||
2.servlet(controller) : 분석 command = hello 이더라 설정파일에서 hello에 맞는 액션클래스로!!
||
3.액션클래스(Model의 입구) : 요청에 맞는 비지니스 로직을 처리하여 request에 값을저장하고
servlet으로 jsp경로 전달
||
4.servlet(controller) : 받아온 jsp경로를 view로 선택
||
5.JSP(View) : request로부터 값을받아들여 (포워딩되어 request영역을 공유,session은 과부하가 우려된다.)
사용자에게 HTML응답해줌
예제2: Model 2 DB연동 X
Java Resources
kame.chap24
BasicController (설정파일없이 서블릿안에서 요청분석
package kame.chap24;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kame.chap24.command.HelloHandler;
import kame.chap24.command.ListHandler;
import kame.chap24.command.NoticeHandler;
import kame.mvc.command.CommandHandler;
public class BasicController extends HttpServlet{
//1단계의 요청을 받음
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
processRequest(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
processRequest(request, response);
}
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
String view=null;
//글로벌 자료형사용하기위해 인터페이스 사용
CommandHandler com = null;
//클라이언트가 어떤한 걸 모델클레스를 요청하는지 알려줄꺼
String command= request.getParameter("command");
if(command.equals("hello")){
com =new HelloHandler();
//모델클래스 분기점
}else if(command.equals("list")){
com =new ListHandler();
}else if(command.equals("notice")){
com =new NoticeHandler();
}
try{
view=com.process(request, response);
}catch(Throwable e){
e.printStackTrace();
}
//5단계, RequestDispatcher를 사용하여 알맞은 뷰로 포워딩
RequestDispatcher dispatcher=request.getRequestDispatcher(view);
dispatcher.forward(request, response);
}
}package kame.chap24.command;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kame.mvc.command.CommandHandler;
public class ByeHandler implements CommandHandler{
@Override
public String process(HttpServletRequest request,
HttpServletResponse response) throws Throwable {
request.setAttribute("bye", "안녕히 가세요!!");
return "/view/bye.jsp";
}
}HelloHandler
package kame.chap24.command;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kame.mvc.command.CommandHandler;
public class HelloHandler implements CommandHandler{
@Override
public String process(HttpServletRequest request,HttpServletResponse response) throws Throwable {
request.setAttribute("hello", "안녕하세요!");
return "/view/hello.jsp";
}
}ListHandler
package kame.chap24.command;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kame.mvc.command.CommandHandler;
public class ListHandler implements CommandHandler{
@Override
public String process(HttpServletRequest request,HttpServletResponse response) throws Throwable {
request.setAttribute("list", "목록을 화면에 리스트 합니다.");
return "/view/list.jsp";
}
}NoticeHandler
package kame.chap24.command;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kame.mvc.command.CommandHandler;
public class NoticeHandler implements CommandHandler {
@Override
public String process(HttpServletRequest request,HttpServletResponse response) throws Throwable {
request.setAttribute("notice", "뉴스를 알려드리겠습니다.");
return "/view/notice.jsp";
}
}kame.mvc.command (액션클래스의 인터페이스 : 다수의 액션클래스에 자료형일치,형태통일화)
CommandHandler
package kame.mvc.command;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//인터페이스
public interface CommandHandler {
public String process(HttpServletRequest request, HttpServletResponse response)throws Throwable;
}kame.mvc.contoller
ControllerUsingFile (요청설정파일을통한 컨트롤러:서블릿)
package kame.mvc.controller;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kame.mvc.command.CommandHandler;
public class ControllerUsingFile extends HttpServlet {
// <커맨드, 핸들러인스턴스> 매핑 정보 저장
//데이터를 담을 HashMap을 생성
private Map commandHandlerMap = new java.util.HashMap();
//ServletConfig : 서블릿이 만들어질때 각각의 서블릿에 생성되는 ServletConfig :비서같은 역활
public void init(ServletConfig config) throws ServletException {
String configFile = config.getInitParameter("configFile");
//Properties 키 = 값 을 구분해서 분리해줌
Properties prop = new Properties();
FileInputStream fis = null;
try {
//getRealPath : 상대경로를 절대경로로 만들어줌
///WEB-INF/commandHandler.properties 를 절대경로로 만듬
String configFilePath = config.getServletContext().getRealPath(configFile);
//commandHandler.properties 설정파일을 파일내용 그대로 읽어옴
fis = new FileInputStream(configFilePath);
//키:값 분리
prop.load(fis);
} catch (IOException e) {
throw new ServletException(e);
} finally {
if (fis != null)
try {
//파일연동시 자원정리
fis.close();
} catch (IOException ex) {
}
}
Iterator keyIter = prop.keySet().iterator();
while (keyIter.hasNext()) {
//command 키값
String command = (String) keyIter.next();
//prop.getProperty(command) : 값(value)를 리턴함
String handlerClassName = prop.getProperty(command);
try {
//Class.forName() : 클래스정보를 문자열(handlerClassName)로 받아서 실제클래스를 찾는다.
Class handlerClass = Class.forName(handlerClassName);
Object handlerInstance = handlerClass.newInstance();
commandHandlerMap.put(command, handlerInstance);
} catch (ClassNotFoundException e) {
throw new ServletException(e);
} catch (InstantiationException e) {
throw new ServletException(e);
} catch (IllegalAccessException e) {
throw new ServletException(e);
}
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
process(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
process(request, response);
}
private void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String command = request.getParameter("command");
CommandHandler handler = (CommandHandler) commandHandlerMap
.get(command);
String viewPage = null;
try {
viewPage = handler.process(request, response);
} catch (Throwable e) {
throw new ServletException(e);
}
RequestDispatcher dispatcher = request.getRequestDispatcher(viewPage);
dispatcher.forward(request, response);
}
}
package kame.mvc.controller;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kame.mvc.command.CommandHandler;
public class ControllerUsingURI extends HttpServlet {
// <커맨드, 핸들러인스턴스> 매핑 정보 저장
//데이터를 담을 HashMap을 생성
private Map commandHandlerMap = new java.util.HashMap();
//ServletConfig : 서블릿이 만들어질때 각각의 서블릿에 생성되는 ServletConfig :비서같은 역활
public void init(ServletConfig config) throws ServletException {
String configFile = config.getInitParameter("configFile");
//Properties 키 = 값 을 구분해서 분리해줌
Properties prop = new Properties();
FileInputStream fis = null;
try {
//getRealPath : 상대경로를 절대경로로 만들어줌
///WEB-INF/commandHandler.properties 를 절대경로로 만듬
String configFilePath = config.getServletContext().getRealPath(configFile);
//commandHandler.properties 설정파일을 파일내용 그대로 읽어옴
fis = new FileInputStream(configFilePath);
//키:값 분리
prop.load(fis);
} catch (IOException e) {
throw new ServletException(e);
} finally {
if (fis != null)
try {
//파일연동시 자원정리
fis.close();
} catch (IOException ex) {
}
}
Iterator keyIter = prop.keySet().iterator();
while (keyIter.hasNext()) {
//command 키값
String command = (String) keyIter.next();
//prop.getProperty(command) : 값(value)를 리턴함
String handlerClassName = prop.getProperty(command);
try {
//Class.forName() : 클래스정보를 문자열(handlerClassName)로 받아서 실제클래스를 찾는다.
Class handlerClass = Class.forName(handlerClassName);
Object handlerInstance = handlerClass.newInstance();
commandHandlerMap.put(command, handlerInstance);
} catch (ClassNotFoundException e) {
throw new ServletException(e);
} catch (InstantiationException e) {
throw new ServletException(e);
} catch (IllegalAccessException e) {
throw new ServletException(e);
}
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
process(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
process(request, response);
}
private void process(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
String command = request.getRequestURI();
if(command.indexOf(request.getContextPath())==0){
//ex> substring으로 앞을짤라 hello.do 만 구해내기
command=command.substring(request.getContextPath().length());
}
CommandHandler handler = (CommandHandler) commandHandlerMap.get(command);
String viewPage = null;
try {
viewPage = handler.process(request, response);
} catch (Throwable e) {
throw new ServletException(e);
}
RequestDispatcher dispatcher = request.getRequestDispatcher(viewPage);
dispatcher.forward(request, response);
}
}bye.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Bye</title>
</head>
<body>
${bye}
</body>
</html>
hello.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello</title>
</head>
<body>
${hello}
</body>
</html>
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>목록</title>
</head>
<body>
${list}
</body>
</html>notice.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>뉴스</title>
</head>
<body>
${notice}
</body>
</html>WEB-INF
commandHandler.properties (요청경로 설정 파일)
hello=kame.chap24.command.HelloHandler list=kame.chap24.command.ListHandler notice=kame.chap24.command.NoticeHandler bye=kame.chap24.command.ByeHandler
commandHandlerURI.properties (요청 URI경로(*.do) 설정 파일)
/hello.do=kame.chap24.command.HelloHandler /list.do=kame.chap24.command.ListHandler /notice.do=kame.chap24.command.NoticeHandler /bye.do=kame.chap24.command.ByeHandler
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
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>mvcMain</display-name>
<!-- Mapping -->
<!-- SimpleController start -->
<servlet>
<servlet-name>SimpleController</servlet-name>
<servlet-class>kame.chap24.SimpleController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SimpleController</servlet-name>
<url-pattern>/simple</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>BasicController</servlet-name>
<servlet-class>kame.chap24.BasicController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BasicController</servlet-name>
<url-pattern>/basic</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ControllerUsingFile</servlet-name>
<servlet-class>kame.mvc.controller.ControllerUsingFile</servlet-class>
<init-param>
<param-name>configFile</param-name>
<param-value>/WEB-INF/commandHandler.properties</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ControllerUsingFile</servlet-name>
<url-pattern>/controllerUsingFile</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ControllerUsingURI</servlet-name>
<servlet-class>kame.mvc.controller.ControllerUsingURI</servlet-class>
<init-param>
<param-name>configFile</param-name>
<param-value>/WEB-INF/commandHandlerURI.properties</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ControllerUsingURI</servlet-name>
<!-- 가상의 확장자 .do -->
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- /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>
실행테스트
command=hello 요청
command=list 요청
1. 파일 : properties 설정파일을 통한 command=notice 요청
2. URI : properties URI 설정파일을 통한 hello.do 요청
'JSP > 기본(Oracle)' 카테고리의 다른 글
| 회원관리 (1) | 2012.06.20 |
|---|---|
| 모델2 : MVC : Model View Controller - DB연동 (0) | 2012.06.20 |
| MVC: Model View Controller 모델2 ( 완전중요) (0) | 2012.06.20 |
| EL(표현언어), JSTL, 국제화 태그 - 예제 (0) | 2012.06.20 |
| EL(표현언어), JSTL, 국제화 태그 (0) | 2012.06.20 |