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 이동
}
}