ํ๋ก ํธ ์ปจํธ๋กค๋ฌ ํจํด
ํ๋ก ํธ ์ปจํธ๋กค๋ฌ ๋์ ์
ํ๋ก ํธ ์ปจํธ๋กค๋ฌ ๋์ ํ
FrontController ํจํด ํน์ง
ํ๋ก ํธ ์ปจํธ๋กค๋ฌ ์๋ธ๋ฆฟ ํ๋๋ก ํด๋ผ์ด์ธํธ์ ์์ฒญ์ ๋ฐ์
ํ๋ก ํธ ์ปจํธ๋กค๋ฌ๊ฐ ์์ฒญ์ ๋ง๋ ์ปจํธ๋กค๋ฌ๋ฅผ ์ฐพ์์ ํธ์ถ
์
๊ตฌ๋ฅผ ํ๋๋ก! / ๊ณตํต ์ฒ๋ฆฌ ๊ฐ๋ฅ
ํ๋ก ํธ ์ปจํธ๋กค๋ฌ๋ฅผ ์ ์ธํ ๋๋จธ์ง ์ปจํธ๋กค๋ฌ๋ ์๋ธ๋ฆฟ์ ์ฌ์ฉํ์ง ์์๋ ๋จ
V1 ๊ตฌ์กฐ
urlPatterns = "/front-controller/v1/*"
/front-controller/v1 ๋ฅผ ํฌํจํ ํ์ ๋ชจ๋ ์์ฒญ์ ์ด ์๋ธ๋ฆฟ์์ ๋ฐ์๋ค์ธ๋ค.
private Map<String, ControllerV1> controllerMap = new HashMap<>();
public FrontControllerServletV1() {
controllerMap.put("/front-controller/v1/members/new-form",new MemberFormControllerV1());
controllerMap.put("/front-controller/v1/members/save",new MemberSaveControllerV1());
controllerMap.put("/front-controller/v1/members",new MemberListControllerV1());
}
key: ๋งคํ URL / value: ํธ์ถ๋ ์ปจํธ๋กค๋ฌ
ControllerV1 controller = controllerMap.get(requestURI);
if(controller==null){
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
๋จผ์ requestURI ๋ฅผ ์กฐํํด์ ์ค์ ํธ์ถํ ์ปจํธ๋กค๋ฌ๋ฅผ controllerMap ์์ ์ฐพ๋๋ค.
๋ง์ฝ ์๋ค๋ฉด 404(SC_NOT_FOUND) ์ํ ์ฝ๋๋ฅผ ๋ฐํํ๋ค.
controller.process(request,response);
์ปจํธ๋กค๋ฌ๋ฅผ ์ฐพ๊ณ controller.process(request, response); ์ ํธ์ถํด์ ํด๋น ์ปจํธ๋กค๋ฌ๋ฅผ ์คํํ๋ค.
๋คํ์ฑ์ ์ํด์ ์ค๋ฒ๋ผ์ด๋ฉ๋ ๋ฉ์๋๊ฐ ํธ์ถ๋๋ค
View ๋ถ๋ฆฌ - v2
public interface ControllerV2 {
MyView process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
}
์ปจํธ๋กค๋ฌ๊ฐ ๋ทฐ๋ฅผ ๋ฐํ
public class MyView {
private String viewPath;
public MyView(String viewPath) {
this.viewPath = viewPath;
}
public void render(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
RequestDispatcher dispatcher = request.getRequestDispatcher(viewPath);
dispatcher.forward(request,response);
}
public class MemberFormControllerV2 implements ControllerV2 {
@Override
public MyView process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
return new MyView("/WEB-INF/views/new-form.jsp");
}
}
๋จ์ํ MyView ๊ฐ์ฒด๋ฅผ ์์ฑํ๊ณ ๊ฑฐ๊ธฐ์ ๋ทฐ ์ด๋ฆ๋ง ๋ฃ๊ณ ๋ฐํํ๋ฉด ๋๋ค.
MyView myView = controller.process(request, response);
myView.render(request,response);
์ด์ ๊ฐ ์ปจํธ๋กค๋ฌ๋ ๋ณต์กํ dispatcher.forward() ๋ฅผ ์ง์ ์์ฑํด์ ํธ์ถํ์ง ์์๋ ๋๋ค.
ControllerV2์ ๋ฐํ ํ์ ์ด MyView ์ด๋ฏ๋ก ํ๋ก ํธ ์ปจํธ๋กค๋ฌ๋ ์ปจํธ๋กค๋ฌ์ ํธ์ถ ๊ฒฐ๊ณผ๋ก MyView ๋ฅผ ๋ฐํ ๋ฐ๋๋ค.
๊ทธ๋ฆฌ๊ณ view.render() ๋ฅผ ํธ์ถํ๋ฉด forward ๋ก์ง์ ์ํํด์ JSP๊ฐ ์คํ๋๋ค.
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-1/dashboard
'Spring > Spring MVC' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[์คํ๋ง MVC] - 9. ํ๋ก ํธ ์ปจํธ๋กค๋ฌ - ์ด๋ํฐ (0) | 2023.02.15 |
---|---|
[์คํ๋ง MVC] - 8. ํ๋ก ํธ ์ปจํธ๋กค๋ฌ - ModelView (0) | 2023.02.14 |
[์คํ๋ง MVC] - 6. MVC ํจํด - ์ ์ฉ , ํ๊ณ (0) | 2023.02.13 |
[์คํ๋ง MVC] - 5. ์๋ธ๋ฆฟ๊ณผ JSP์ ํ๊ณ / MVC ํจํด์ ๋ฑ์ฅ (0) | 2023.02.13 |
[์คํ๋ง MVC] - 4. HTTP ์๋ต ๋ฐ์ดํฐ ( ํ ์คํธ / HTML / API ) (0) | 2023.02.12 |