■ 모델 2 기반의 간단한 MVC 패턴 구현방법
01. 컨틀로러의 역할을 하는 서블릿 클래스
SampleController.java |
package ch21.controller;
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;
public class SampleController extends HttpServlet { // 1단계 GET 방식으로 요청을 받음 : proRequest 메소드 전달 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { proRequest(request, response); }
// 1단계 POST 방식으로 요청을 받음 : proRequest 메소드 전달 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { proRequest(request, response); }
private void proRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 2단계 Request 객체로부터 사용자의 요청을 파악하는 코드 String cmd = request.getParameter("cmd"); // 3단계 사용자의 요청에 알맞은 작업을 처리하는 코드 Object resultObj = null; if (cmd.equals("eng")) { resultObj = "Hello!!!"; } else if (cmd.equals("kor")) { resultObj = "안녕하세요!!!"; } else { resultObj = "'eng' 혹은 'kor' 중 하나로 타입을 결정하세요."; } // 4단계 Request 객체의 result 속성에 처리 결과를 지정하는 코드 request.setAttribute("result", resultObj); // 5단계 RequestDispatcher를 사용하여 알맞은 뷰(JSP 페이지)로 포워딩 RequestDispatcher dispatcher = request.getRequestDispatcher("/ch21/sampleView.jsp"); dispatcher.forward(request, response); } }
|
02. 뷰의 역할을 하는 JSP
01) *.jar파일 다운 받기
① JSTL 스펙 라이브러리 → jstl.jar
② JSTL 구현 라이브러리 → standard.jar
02) ch12폴더를 만든 후 sampleView.jsp를 추가혀아 다음과 같이 코딩한다.
sampleView.jsp |
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>간단한 컨트롤러의 사용 예</title> </head> <body> <%-- result 속성의 값을 result 변수에 저장한다.--%> <c:set var = "result" value = "${result}"/>
<%-- result 변수의 내용을 화면에 출력한다.--%> <c:out value = "${result}"/> </body> </html> |
실행과정 |
![](https://t1.daumcdn.net/cfile/tistory/17525237503EEBD105)
|
① 출력화면 - URL : http://localhost:8181/ch21/SampleController |
![](https://t1.daumcdn.net/cfile/tistory/126EBC47503EEF1D05)
|
② 출력화면 - URL : http://localhost:8181/ch21/SampleController?cmd=eng
|
![](https://t1.daumcdn.net/cfile/tistory/123B703B503EEC1D31)
|
③ 출력화면 - URL : http://localhost:8181/ch21/SampleController?cmd=kor |
![](https://t1.daumcdn.net/cfile/tistory/186A4B3B503EEC1E0F)
|
④ 출력화면 - URL : http://localhost:8181/ch21/SampleController?cmd=? |
![](https://t1.daumcdn.net/cfile/tistory/202D613B503EEC1E3A)
|