웹프로그래밍/JSP_Servlet
FrontController
marmelo12
2023. 11. 1. 23:10
반응형
서블릿은 하나의 URL과 매핑해서 사용자의 요청에 대한 처리를 할 수 있다.
다만, 모든 요청에 대해 서블릿을 만들기에는 너무 많은 서블릿클래스와 유지보수가 어려워짐.
이럴때 MVC패턴을 적용한 FrontController 기법을 이용할 수 있다.
- FrontController를 하나만 두고, 요청을 분기한다.
a.jsp --> web.xml --> Front-Controller --> c.jsp
↑↓
Controller(~~~Action)
↑↓
DAO, DTO
↑↓
DB
하나의 FrontController에서 초기화 단계에 요청에 대한 URL을 Action(비즈니스 로직처리->모델영역)과 함께 묶어서 저장.
-> 그렇기에 기본적으로 FrontController는 모든 요청을 우선 받아들임.
샘플 코드
@WebServlet("/*.do")
public class FrontController extends HttpServlet {
private static final long serialVersionUID = 1L;
private Map<String, Command> commandByRequestURL = new HashMap<String, Command>();
public FrontController() {
commandByRequestURL.put("/login.do", new UserLoginCommand());
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
String actionPath = request.getContextPath().substring(request.getRequestURI().length());
Command cmd = commandByRequestURL.get(actionPath);
if(cmd != null) {
// 처리
cmd.execute(request, response);
}
else {
// 에러반환.
}
}
}
반응형