The Debugging Chronicles : "코드의 미학"

[Spring] ViewResolver 본문

Spring

[Spring] ViewResolver

sweetseonah1004 2024. 10. 7. 14:20

 

DispatcherServlet은 의존성을 2개 가지고 있는데

handlerMapping과 ViewResolver이다

POJO이다

어디로 갈지를 관여한다.

 

멤버변수는

prefix와 suffix가 있는데

setter로 의존성을 주입한다.

 

어디로 가야할지 관연하는 부분에서

어디로 가야할 부분에 접두사(./)랑 접미어(.jsp)를 붙여서 완성시킨다.

 

 


package com.koreait.app.view.controller;

public class ViewResolver {
	private String prefix;
	private String suffix;
	
	public String getPrefix() {
		return prefix;
	}
	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}
	public String getSuffix() {
		return suffix;
	}
	public void setSuffix(String suffix) {
		this.suffix = suffix;
	}
	
	public String getView(String path) { 
		return prefix+path+suffix;
	}
}

 

package com.koreait.app.view.controller;

import java.io.IOException;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("*.do")
public class DispatcherServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private HandlerMapping handlerMapping;
	private ViewResolver viewResolver;
       
    public DispatcherServlet() {
        super();
    }
    
    public void init() {
    	this.handlerMapping = new HandlerMapping();
    	this.viewResolver = new ViewResolver();
    	this.viewResolver.setPrefix("./");
    	this.viewResolver.setSuffix(".jsp");
    }    

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

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doAction(request, response);
	}
	
	private void doAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 1. 사용자(클라이언트,브라우저)의 요청 추출
		String uri=request.getRequestURI();
		String command=uri.substring(uri.lastIndexOf("/"));
		
		// 2. 요청에 해당하는 Controller 기능을 수행
		Controller controller=this.handlerMapping.getController(command);
								// 팩토리 패턴을 활용하는 handlerMapping
		String path=controller.execute(request, response);
		
		// 3. 응답(페이지 이동)
	}
}