티스토리 뷰

프로젝트를 톰캣 서버를 사용하여 run할 때, 기본 경로는 web.xml내에 welcome file로 지정되어 있는 파일이다. 지금까지는 그냥 index.jsp나 index.html 을 생성해서 default 값을 사용했다.

 

하지만, mvc model2 패턴을 사용하여 프로젝트를 구성한다면 index.jsp 또한 ActionFactory를 사용하여 마찬가지로 index.html에서 Controller에게 요청하여 index.jsp 로 이동하게끔 구성하는 방법도 있다. 

 

이 방법을 사용하면, 물론 설계 초반에 좀 더 손이 가겠지만, index.jsp 파일을 url 직접적으로 노출시키지 않고 또한 header나 footer를 고정시킨 상태에서 그 내부 컨텐츠를 좀 더 쉽게 변경할 수 있다는 장점이 있다. 

방법은 생각보다 간단하다. 바로 한번 확인해보자.


우선 프로젝트가 실행됐을 때, 곧 바로 호출되는 index.html 파일부터 살펴보면, 

 

◎index.html

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<meta http-equiv="refresh" content = "0; url=NonageServlet?command=index">
	<title>index.html</title>
	<!-- 
	html의 <meta> 태그를 이용하여 서블릿에게 요청 사항을 전달
	1. http-equiv: 요청 사항에 대한 결과를 받기 전 웹 브라우저를 마치 새로고침 하는 것 처럼
    			초기화 할 수 있는 값을 설정 => "refrash"
    2. content : 요청할 주소(즉, 대상) 
              url = 대상
	 -->
</head>
<body>

</body>
</html>

위와 같이 <meta> 태그로 콘텐츠의 url 경로를 설정해주면, 요청 사항에 대한 결과를 받기 전에 새로고침한 효과와 함께 해당 url로 이동한다.

 

Servlet 쪽은 일반적인 MVC 구조와 동일하다. 

 

◎NonageServlet

package com.choonham.controller;

import java.io.IOException;

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.choonham.controller.action.Action;

/**
 * Servlet implementation class NonageServlet
 */
@WebServlet("/NonageServlet")
public class NonageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public NonageServlet() {
        super();
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String command = request.getParameter("command");
		System.out.println("웹 브라우저로부터 요청 받음 : " + command);
		
		ActionFactory af = ActionFactory.getInstance();
		Action action = af.getAction(command);
		
		if(action != null) {
			action.execute(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		doGet(request, response);
	}

}

 

실제 index.jsp로 포워딩하는 기능을 하는 객체는 IndexAction 객체

 

◎ IndexAction.java

package com.choonham.controller.action;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class IndexAction implements Action {

	public IndexAction() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url = "/index.jsp";
		
		RequestDispatcher rd = request.getRequestDispatcher(url);
		rd.forward(request, response);
		
	}

}

이제ActionFactory에서 command = index 값을 받을 때, 객체 생성을 해주면 끝!

 

◎ActionFactory.java

package com.choonham.controller;

import com.choonham.controller.action.Action;
import com.choonham.controller.action.IndexAction;

public class ActionFactory {
	
	private static ActionFactory instance = null;
	
	private ActionFactory() {
		super();
	}
	
	public static ActionFactory getInstance() {
		if(instance == null) {
			instance = new ActionFactory();
		}
		return instance;
	}
	
	public Action getAction(String command) {
		Action action = null;
		
		if(command.equals("index")) {
			action = new IndexAction();
		}
		
		return action;
	}

}

 

그럼 아래와 같이 구성한 index.jsp의 url을 직접적으로 드러내지 않고 빠르게 로드할 수 있다.

 

◎index.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>
<%@ include file = "header.jsp" %>

	여기에 상품을 진열합니다.

<%@ include file = "footer.jsp" %>
</body>
</html>

 

또한 위와 같이 header와 footer를 따로 가지고 있는 구조를 가지고 있기 때문에 해당 header, footer는 고정한 상태로 따로 내부 content만 제어하기도 쉬워진다. 

 

Comments