MVC 패턴(링크)은 거의 model 2만 사용한다.
◎ .do & .action
- MVC패턴에서는 요청을 .jsp로 직접 하지 않고 Action(클래스명)이라는 자바파일을 실행하게 됩니다. 이 자바파일에서 비즈니스로직을 실행하고 뷰에 필요한 데이터만 jsp로 넘겨줍니다. 그래서 .do 또는 .action과 같은 방식으로 URL을 요청하게 됩니다. 이것을 Controller에서 맵핑하기 위해 web.xml에서 설정을 해야합니다.
1. web.xml
- Controller에서 맵핑을 하기 위한 설정, URI을 통해 ~~~.do의 형식으로 명령어 전달.
<servlet>
<servlet-name>FrontController</servlet-name>
<servlet-class>net.board.controller.FrontController</servlet-class>
<init-param>
<param-name>configFile</param-name>
<param-value>/WEB-INF/FrontController.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>FrontController</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
2. properties
- 요청받는 URI에 따른 Handler를 맵핑시킬 때 사용하는 설정 파일, 이 파일을 사용하면 새로운 명령어가 추가되어도 Controller의 코드를 직접 수정 할 필요없음. Controller의 init()에서 읽혀짐.
- 왼쪽은 URI를 적으며 key값, 오른쪽은 맵핑할 Handler 클래스를 적으며 value값
/login.do=auth.command.LoginHandler
/logout.do=auth.command.LogoutHandler
3. CommandHandler, NullHandler
- CommandHandler(인터페이스) : Command들의 메서드를 구현하기 위한 인터페이스
- NullHandler(클래스) : property에 Handler가 존재하지 않을 때 수행될 클래스(CommandHandler 구현)
package net.member.command;
import javax.servlet.http.*;
public interface CommandHandler { // Command들의 메서드를 구현하기 위한 인터페이스
public String process(HttpServletRequest request,HttpServletResponse response) throws Exception;
}
package mvc.command;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class NullHandler implements CommandHandler {
@Override
public String process(HttpServletRequest req, HttpServletResponse res) throws Exception {
res.sendError(HttpServletResponse.SC_NOT_FOUND);
return null;
}
}
4. Controller
- 요청한 URI에 따라 맵핑된 Handler 클래스를 호출하며 그 후 결과를 받아 view로 forward해줌.
- init()에서 propertie를 읽어와 모든 Handler를 Map저장함.
@WebServlet("/FrontController")
public class FrontController extends HttpServlet {
private Map<String, CommandHandler> commandHandlerMap = new HashMap<>(); // 모든 Handler를 저장할 Map
public void init() throws ServletException {
String configFile = getInitParameter("configFile");
Properties prop = new Properties();
String configFilePath = getServletContext().getRealPath(configFile);
try (FileReader fis = new FileReader(configFilePath)) {
prop.load(fis); // properties 읽어옴
} catch (IOException e) {
throw new ServletException(e);
}
Iterator keyIter = prop.keySet().iterator();
while (keyIter.hasNext()) {
String command = (String) keyIter.next(); // key값 (/login.do)
String handlerClassName = prop.getProperty(command); // value값 (auth.command.LoginHandler)
try {
Class<?> handlerClass = Class.forName(handlerClassName);
CommandHandler handlerInstance =
(CommandHandler) handlerClass.newInstance();
commandHandlerMap.put(command, handlerInstance); // Map에 저장
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
throw new ServletException(e);
}
}
}
protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String command=request.getRequestURI(); // /project/hello.do
String contextPath=request.getContextPath(); // /project
if (command.indexOf(contextPath) == 0) {
command = command.substring(contextPath.length()); // /hello.do
}
CommandHandler handler = commandHandlerMap.get(command); // URI에 맞는 Handler 획득
if (handler == null) {
handler = new NullHandler();
}
String viewPage = null;
try {
viewPage = handler.process(request, response); // 맵핑된 Handler의 메서드 수행 후 리턴값으로 viewpage 반환
} catch (Throwable e) {
throw new ServletException(e);
}
if (viewPage != null) {
RequestDispatcher dispatcher = request.getRequestDispatcher(viewPage);
dispatcher.forward(request, response); // viewpage로 forward
}
}
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);
}
}
4. ~~~Handler.java (command 패키지)
- 각종 Command을 수행하는 모듈, CommandHandler 인터페이스를 구현함.
5. ~~Service.java (service 패키지)
- DAO의 보조적인 역할을 하는 클래스, DAO에서 하는 여러 작업을 하나의 행동으로 동작하게 해줌.
6. DAO, DTO
- DB에 접근하기 위한 객체
7. View(jsp)
- 클라이언트에게 보여질 화면(View)
'Web > JSP&Servlet' 카테고리의 다른 글
서블릿(Servlet) (0) | 2020.08.28 |
---|---|
커스텀 태그(Custom Tag) (0) | 2020.08.28 |
JSP 레이아웃 INCLUDE하기 (0) | 2020.08.13 |
파일 업로드 (0) | 2020.08.07 |
에러페이지 (0) | 2020.08.07 |