/**
 * ÀÌ ¼Ò½º´Â Spring ÇÁ·¹ÀÓ¿öÅ© ¿öÅ©ºÏ¿¡¼­ »ç¿ëÇÑ ¿¹Á¦ ¼Ò½ºÀÔ´Ï´Ù. 
 * ÀÌ ¼Ò½º´Â ¸ðµç °³¹ßÀÚµéÀÌ ÀÚÀ¯·Ó°Ô ¼öÁ¤ ¹× ¹èÆ÷ÇÒ ¼ö ÀÖ½À´Ï´Ù. 
 * ´Ü, ÀÌ ¼Ò½º¸¦ ±â¹ÝÀ¸·Î »õ·Î¿î ¾ÖÇÃ¸®ÄÉÀÌ¼ÇÀ» °³¹ßÇÒ °æ¿ì ÃâÃ³¸¦ ¸í½ÃÇØ ÁÖ½Ã¸é µË´Ï´Ù. 
 */
package net.javajigi.common.web;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class MyUrlFilenameViewController implements Controller {
	protected final Log logger = LogFactory.getLog(getClass());
	
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) {
		String contextPath = request.getContextPath();
		String uri = request.getRequestURI();
		
		if( logger.isDebugEnabled() ) {
			logger.debug("URI : " + uri);
			logger.debug("ContextPath : " + contextPath);
		}
		
		int begin = 0;
		if( (contextPath==null)||(contextPath.equals("")) ) {
			begin = 0;
		} else {
			if( uri.startsWith("/") ) {
				begin = contextPath.length();
			} else {
				begin = contextPath.length() - 1;
			}
		}
		
		if( logger.isDebugEnabled() ) {
			logger.debug("Begin : " + begin);
		}
		
		int end;
		if (uri.indexOf(";") != -1) {
			end = uri.indexOf(";");
		} else if (uri.indexOf("?") != -1) {
			end = uri.indexOf("?");
		} else {
			end = uri.length();
		}
		String fileName = uri.substring(begin, end);
		if (fileName.indexOf(".") != -1) {
			fileName = fileName.substring(0, fileName.lastIndexOf("."));
		}
		
		for (Enumeration en = request.getParameterNames(); en.hasMoreElements();) {
			String attribute = (String) en.nextElement();
			Object attributeValue = request.getParameter(attribute);
			
			if( logger.isDebugEnabled() ) {
				logger.debug("set Attribute in Request : " + attribute + "=" + attributeValue);
			}

			request.setAttribute(attribute, attributeValue);
		}

		return new ModelAndView(fileName);
	}
}
