본문 바로가기

콩's EDUCATION/콩's SPRING

[Kitri] Spring MVC 구조 분석

HelloController.java


// 스프링 mvc 패턴 구조 분석


public class HelloController implements Controller {

@Override

public String handleRequest(HttpServletRequest request, HttpServletResponse response) {

// 화면 뷰 이름 리턴

request.setAttribute("hello", "hello Spring");

return "Hello.jsp";

}

}


// 가장 중요

// Spring API에서 제공하는 것


public class HandlerMapping {

private HashMap<String, Controller> mappings;

public HandlerMapping(){

mappings = new HashMap<String, Controller>();

mappings.put("hello.ht", new HelloController());

}

public Controller getController(String path){

return mappings.get(path);

}

}


import java.io.IOException;


import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class DispatcherServlet extends HttpServlet {

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

String path = request.getRequestURI();

String[] parse = path.split("/");

// "/chap6-..../hello.htm

String cont = parse[parse.length-1];

// 결과는 /hello.htm 이것만 나온다.

HandlerMapping mapping = new HandlerMapping();

// 1. uri ; controller 맵핑 정보

Controller controller = mapping.getController(cont);

// 2. Controller 생성

String view = controller.handleRequest(request, response);

// 3. view 생성(jsp파일명)

RequestDispatcher dispatcher = request.getRequestDispatcher(view);

dispatcher.forward(request, response);

// 4. jsp 이동

}

}


import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/// 모든 컨트롤러들은 handleRequest 메소드 오버라이딩
public interface Controller {
public String handleRequest(HttpServletRequest request, HttpServletResponse response);
}

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Hello.htm</title>
</head>
<body>
hello.htm 결과
<%request.setCharacterEncoding("euc-kr"); %>
11<br>
<%= request.getAttribute("hello") %><br>
11
<br>
${requestScope.hello}
</body>
</html>


user.zip