팀 프로젝트/Web

Controller 기능 별 class 정리 및 Front Controller 정리

개발자가 되고 싶은 곰 2024. 8. 21. 22:23

1. ActionForward 작성

//ActionForward class로 reirect 방식 / path(넘어갈 경로) 를 받을 수 있는 새로운 형식을 만들어 줍니다.

public class ActionForward {
	private String path;
	private boolean redirect;
	
	public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}
	public boolean isRedirect() {
		return redirect;
	}
	public void setRedirect(boolean redirect) {
		this.redirect = redirect;
	}
}

 

 

2. Interface 작성

//모든 Controller가 ActionForward 메서드를 가져야하니 interface로 메서드 강제화를 해줍니다.

public interface Action {
	ActionForward execute(HttpServletRequest request, HttpServletResponse response);
}

 

 

3. HandlerMapper(싱글톤 패턴) 작성

public class HandlerMapper {
	//Map 에 요청과 Action 값을 저장할 수 있도록 만들어 줍니다
	private Map<String, Action> mapper;
	
	public HandlerMapper() {
		//HashMap으로 Map 을 초기화해주고
		this.mapper = new HashMap<String, Action>();
		
		//HashMap에 요청과 Action 값을 추가해줍니다.
		//MainPage Action
		//Page 이동 Action
		this.mapper.put("/main.do", new MainpageAction()); //메인 페이지 이동
		
		//기능 Action
		
		//-------------------------------------------------------------------------------------------------
		//Member Action
		//Page 이동 Action
		this.mapper.put("/View에서정할듯.do", new LoginPageAction()); //로그인 가입 페이지 이동
		this.mapper.put("/View에서정할듯.do", new SignUpPageAction()); //회원 가입 페이지 이동
		
		//기능 Action
		this.mapper.put("/View에서정할듯.do", new LoginAction()); //로그인 기능
		this.mapper.put("/View에서정할듯.do", new SignUpAction()); //회원가입 기능
		this.mapper.put("/View에서정할듯.do", new SmsSendAction()); //문자 인증번호 발송
		
		//-------------------------------------------------------------------------------------------------
		//MyPage Action
		//Page 이동 Action
		this.mapper.put("/View에서정할듯.do", new MypagePageAction()); //MyPage 페이지 이동
		this.mapper.put("/View에서정할듯.do", new ChangeMemberPageAction()); //회원 정보 수정 페이지 이동
		
		//기능 Action
		this.mapper.put("/View에서정할듯.do", new DeleteMemberAction()); //회원 탈퇴 기능
		this.mapper.put("/View에서정할듯.do", new MyBoardAction()); //내가 전체 게시판에 작성한 글 확인
		this.mapper.put("/View에서정할듯.do", new MyCrewBoardAction()); //내가 크루 게시판에 작성한 글 확인		
		this.mapper.put("/View에서정할듯.do", new CerwMemberAction()); //크루 인원 확인 기능
		this.mapper.put("/View에서정할듯.do", new BabyMemberAction()); //크루 신규 인원 확인 기능
		
		//-------------------------------------------------------------------------------------------------
		//BoardOnePage Action
		//이동 Action
		this.mapper.put("/View에서정할듯.do", new BoardUpdatePageAction()); //작성글 수정 페이지 이동
		
		//기능 Action
		this.mapper.put("/View에서정할듯.do", new BoardDeleteAtion()); //작성글 삭제 기능
		//-------------------------------------------------------------------------------------------------
	}
	
	//요청을 받아와 Action 을 반환해줍니다.
	public Action getAction(String command) {
		return this.mapper.get(command);
	}
	
}

 

 

4. FrontCotroller 작성

//view(Web)에서 보내는 Xxx.do 모든 요청을 받아옵니다.
@WebServlet("*.do")
public class FrontController extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private HandlerMapper mapping;
    public FrontController() {
        super();
       mapping = new HandlerMapper();
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doAction(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		doAction(request, response);
	}

	public void doAction(HttpServletRequest request, HttpServletResponse response) {
		//1. 서버 주소를 받아서 요청값 추출 및 확인
		String url = request.getRequestURI(); // 서버 전체 URL(주소)를 받아옵니다
		String cp = request.getContextPath(); // context Path 를 받아옵니다.
		String command = url.substring(cp.length()); // URL에서 context Path 길이 만큼 잘라와 요청을 확인합니다.
		//command 로그
		System.out.println("요청 : "+command);
		
		Action action = this.mapping.getAction(command); // 핸들러 맵핑에서 맞는 Action만 가져와서 사용해줍니다.
		ActionForward forward = action.execute(request, response);
		
		//forward 가 null 이면 요청이 없이 들어온 것이기 때문에
		// 잘못된 요청으로 페이지를 넘겨야합니다.
		if(forward == null) {
			//잘못된 요청으로 404 오류를 띄워 페이지를 이동시킵니다.
			try {
				response.sendRedirect("main.jsp");;
				System.out.println("forward null 로그");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		//forward 가 null 이 아니라면 요청값이 있는 것이기 때문에
		// Redirect(리다이렉트) / Forward(포워드) 인지 구분해줍니다.
		else {
			//만약 forward.isRedirect 가 true 일때 실행됩니다.
			if(forward.isRedirect()) {
				try {
					//forward 로 받아온 주소 값을 등록하여 페이지만 이동합니다.
					response.sendRedirect(forward.getPath());
					System.out.println("Redirect 요청 로그");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			//만약 forward.isRedirect 가 false 일때 실행됩니다.
			else{
				//request 내장 메서드인 RequestDispatcher 에 주소를 입력해줍니다.
				RequestDispatcher dispatcher = request.getRequestDispatcher(forward.getPath());
				try {
					//데이터를 넘겨야하니 forward 방식으로 값을 같이 넘겨줍니다.
					dispatcher.forward(request, response);
					System.out.println("Forward 요청 로그");
				} catch (ServletException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}

 

728x90