Shop [ FrontController ]

양혜정·2024년 4월 27일
0

javascript_web

목록 보기
74/81

Properties

  • WEB-INF -> properties 파일 생성

-> 주석문 : #

-> 한글/공백 불가

-> Context Path 명 이후부터 표시

~~/=패키지명.클래스명(첫글자는 대문자로)
Ex)
/index.up=common.controller.IndexController

Servlet

-> 생성한 properties 파일 location 복사 후 Servlet 생성 실행하기

  • description : servlet 설명문(사용자가 웹에서 *.up 을 했을 경우 이 서블릿이 응답을 해주도록 한다.)

  • Initialization parameters
    add
    -> name : 지정이름
    -> value : 복사한 location 붙여넣기
    -> description : mapping 설명문(*.up에 대한 클래스의 매핑파일)

  • URL mapping : edit 하여 '*.마지막글자' 로 변경

-> constructors from superclass 체크 해제
-> init / doGet / doPost 체크

생성 후 value 에 빨간줄 에러가 뜰 시
-> value 에 각 \ 앞에 \ 를 하나 더 작성해 주면 된다.

init

  • WAS 가 구동된 이후 1번만 실행
private Map<String, Object> cmdMap = new HashMap<>();
public void init(ServletConfig config) throws ServletException{
// === 특정 파일에 있는 내용 읽어오기 === //
FileInputStream fis = null;
String props = config.getInitParameter("Servlet지정이름");
// props = Servlet 에 지정한 value 값(location)
try{
	fis = new FileInputStream(props);
    Properties pr  = new Properties();
    pr.load(fis);
    // fis 객체를 사용하여 props(location 위치의 파일)을 읽어
    // pr 에 load 한다. ( 왼쪽 key, 오른쪽 value 로 인식 )
    
    Enumeration<Object> en = pr.keys();
    // pr에 저장한 모든 key 값들 가져오기
    
    while(en.hasMoreElements()){	// 저장된 key 값이 있으면
    	String key = (String)en.nextElement();
        // object 를 string 타입으로 casting 해주기
        String classname = pr.getProperty(key);
        // value 값 (class 위치)
        
        if(className != null){
        	className = className.trim();	// 공백 대비
            // === 1. 클래스화 === //
            Class<?> cls = Class.forName(className);
            // className 위치 클래스화하여 객체
            
            // 생성자를 만들 수 있는 객체
            Constructor<?> constrt = cls.getDeclaredConstructor();
           
           // === 2. 인스턴스화 === //
            Object obj = constrt.newInstance();
            
            // === 3. Mapping === //
            cmdMap.put(key,obj);
        }	// end of if------------------
    }	// end of while---------------------
} catch(FileNotFoundException e){
	System.out.println("~~ value값인 properties 파일 location 존재 X");
} catch(ClassNotFoundException e){
	System.out.println("클래스명의 클래스가 존재 X")
} catch(Exception e){
	e.printStackTrace();
}
}	// end of init()-------------------

doGet / doPost

// === 웹브라우저 주소창입력 === //
String uri = request.getRequestURI();
String key = uri.substring(request.getContextPath().length());
AbstractController action = (AbstractController) cmdMap.get(key);
if(action == null){
	System.out.println(">>> " + key + " 은 URI 패턴에 매핑된 클래스는 없습니다. <<<");
}
else{
	try{
    	action.execute(request, response);
        
        // === 나만의 loot 지정 === //
        boolean bool = action.isRedirect();
       	String viewPage = action.getViewPage();
        
        if(!bool){	// => forward
        	// 특징 : forward 되어진 페이지로 데이터 전달 가능
        	if(viewPage != null){
            	RequestDispatcher dispatcher = request.getRequestDispatcher(viewPage);
                dispatcher.forward(request,response);
            }
        }
        else{	// sendRedirect
        	// 특징 : 단순 페이지 이동, 데이터 전달 X
        	if(viewPage != null){
            	response.sendRedirect(viewPage);
            }
        }	// end of if~else------------------
    } catch(Exception e){
    	e.printStackTrace();
    }
}

xml

  • ctxPath 뒤에 아무것도 존재하지 않을때 첫페이지로 보이게 하기
<welcome-file>~~</welcome-file>

정리

  • common.controller -> FrontController.java

0개의 댓글

관련 채용 정보