본문 바로가기
Backend/JAVA

MVC Servlet - controller 작성하기 - 3

by YERIEL_염주둥 2020. 5. 13.
728x90

MVC Servlet - controller 작성하기 - 2 https://r-0o0-j.tistory.com/100

 

MVC Servlet - controller 작성하기 -2

MVC Servlet - controller 작성하기 - 1 https://r-0o0-j.tistory.com/99 [#006888] 1. 기본 생성된 클래스에 init( ) 메서드, destroy( ) 메서드 알아보기 [1] init( ) 메서드란? servlet이 객체화 되었을 때 초..

r-0o0-j.tistory.com

1. controller에 분기 작업하기

먼저 HttpServletRequest , HttpServletResponse에 대해 알아보면

  • HttpServletRequest는 호출에 관련된 정보가 담겨있다.
  • HttpServletResponse는 응답에 관련된 정보가 담겨 있다.
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String uri = request.getRequestURI();
		System.out.println(uri + " <- uri");
		String contextpath = request.getContextPath();
		System.out.println(contextpath + " <- contextpath");
		uri = uri.replace(contextpath, "");
		System.out.println(uri + " <- contextpath가 제거된 uri");

		String forwardPath = null;
		if("/main.yeriel".equals(uri)) {
			forwardPath = "main.jsp";
		}else if("/mypage.yeriel".equals(uri)) {
			forwardPath = "mypage.jsp";
		}else {
			response.setStatus(404);
		}
		if(forwardPath != null) {
			request.getRequestDispatcher("/WEB-INF/views/"+forwardPath).forward(request,response);
		}
	}

 

서블릿 자체에서 화면을 직접 그리기가 힘들다.
웹 화면에 필요한 정보 : Encoding, header, ContentType 등 담아야 할 코드가 많기 때문에
포워드의 기술을 활용하여 화면 렌더링을 jsp로 전달 한다. (모든 web에서 통일)

1. 전체 경로는 uri 매개변수에 담고 contextPath는 바뀔 우려가 있음으로 불안한 요소가 되므로 replce 메서드를 활용해서 contextPath를 제거한 후 뒤의 경로만 가지고 분기 작업을 한다.

2. forward : request, response 객체를 getRequestDispatcher에 서술된 페이지(인수)로 위임한다.

3. 지정되지 않은 경로가 입력 됬을 경우에는 response.setStatus(404); 로 빈 화면이 아니라 404 화면을 띄워준다.

지정 되지 않은 경로
지정 된 경로

반응형

'Backend > JAVA' 카테고리의 다른 글

Connection Pool 설정하기  (0) 2020.05.14
Connection Pool 이론  (0) 2020.05.14
MVC Servlet - controller 작성하기 -2  (0) 2020.05.13
MVC Servlet - controller 작성하기 - 1  (0) 2020.05.13
MVC (model view controller) 패턴  (0) 2020.05.13

댓글