상세 컨텐츠

본문 제목

MVC이해

스프링

by e7e 2022. 4. 27. 08:18

본문

DispatchServlet.java

@WebServlet(name = "action", urlPatterns = { "*.do" })
public class DispatchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	private HandlerMapping handleMapping;
	private ViewResolver viewResolver;
	

    @Override
    public void init() throws ServletException {
        handleMapping = new HandlerMapping();
        viewResolver = new ViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/myview/");
        viewResolver.setSuffix(".jsp");
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}
	
	private void process(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException {
		String uri = request.getRequestURI();
		String path = uri.substring(uri.lastIndexOf("/"));
		System.out.println(path);
		
		Controller ctl = handleMapping.getController(path);
		String viewName = ctl.handleRequest(request, response);
		String forwardUrl = viewResolver.getView(viewName);
		
		request.getRequestDispatcher(forwardUrl).forward(request, response);
	
	}

}

Controller.java

public interface Controller {
	String handleRequest(HttpServletRequest request,HttpServletResponse response);
}

MyController.java

public class MyController implements Controller {

	@Override
	public String handleRequest(HttpServletRequest request, HttpServletResponse response) {		
		request.setAttribute("merong","Hello Merong" );
		return "mypage";
	}

}

 

HandlerMapping.java

public class HandlerMapping {
	
	private Map<String, Controller> mappings;
	
	public HandlerMapping() {
		mappings = new HashMap<String, Controller>();
		mappings.put("/aaa.do", new MyController());
	}

	public Controller getController(String path) {
		return mappings.get(path);
	}
	
}

ViewResolver.java

public class ViewResolver {
	public String prefix;
	public String suffix;
	
	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

	public void setSuffix(String suffix) {
		this.suffix = suffix;
	}
	
	public String getView(String viewName) {
		return prefix + viewName + suffix;
	}

}

'스프링' 카테고리의 다른 글

WYSIWYG 에디터 CKEditor4 이미지 업 설정  (1) 2022.04.29
초간단 WebSocket 채팅  (16) 2022.04.28
HttpClient  (5) 2022.04.27
SQL로그 출력  (0) 2022.04.17
pom.xml등 설정파일 긁어가깅  (0) 2022.04.17

관련글 더보기