/*
 * 作成日: 2004/01/05
 *
 */
package openolap.viewer.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import openolap.viewer.common.CommonSettings;

/**
 */
public class Controller extends HttpServlet {

	// サーブレットの初期化処理
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}

	// サーブレットの終了処理
	public void destroy() {
	}

	// HTTPリクエストで実行される処理
	protected void processRequest(
		HttpServletRequest request,HttpServletResponse response) 
		throws ServletException,java.io.IOException {

		// 初期化
		ServletContext context = getServletConfig().getServletContext();
		if ( context.getAttribute("apCommonSettings") == null ) {
			InitializeStatus.initApStatus(context);
		}

		// 文字コード設定
		request.setCharacterEncoding("Shift_JIS");


		String page;
		try {
			// 呼び出す業務処理を選択
			RequestHelper helper = new RequestHelper(request, response, getServletConfig());
			Command command = helper.getCommand();
	
			if (command == null) { throw new IllegalStateException(); }
			if (context == null) { throw new IllegalStateException();	}

			// 業務処理呼び出し
			page = command.execute(helper, (CommonSettings) context.getAttribute("apCommonSettings"));
		} catch(Exception e) {
			e.printStackTrace();
			return;
		}
	
//System.out.println("controller page:" + page);
	
			//制御をリクエストに対応するページにディスパッチする
			if(page != null) {
				dispatch(request,response,page);
			}

	}

	// HTTP GETの処理
	protected void doGet(
		HttpServletRequest request,
		HttpServletResponse response)
		throws ServletException, IOException {

		processRequest(request,response);
	}

	// HTTP POSTの処理
	protected void doPost(
		HttpServletRequest request,
		HttpServletResponse response)
		throws ServletException, IOException {

		processRequest(request,response);
	}

	//	JSPへのDispatcher処理
	protected void dispatch(
		HttpServletRequest request,
		HttpServletResponse response,
		String page) 
		throws ServletException,java.io.IOException {

		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(page);
		dispatcher.forward(request,response);
	}

}
