2014년 5월 19일 월요일

[Java]MVC방식에 FrontController pattern 적용

1.index.html
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Insert title here</title>
  6. </head>
  7. <body>
  8.     <ol>
  9.         <li>
  10.             <a href="/web/test/first">/first</a>
  11.             [controller] --(forward)--> [/view/first_view.jsp]
  12.         </li>
  13.         <li>
  14.             <a href="/web/test/second">/second</a>
  15.             [controller] --(forward)--> [/view/second_view.jsp]
  16.         </li>
  17.     </ol>
  18. </body>
  19. </html>
2.Front.java
  1. package web;
  2. import java.io.IOException;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.annotation.WebServlet;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. @WebServlet("/test/*")
  9. /*
  10.  * mapping url pattern
  11.  *  "/*" : 모든 요청
  12.  * "*.do" : 확장자가 do인 요청
  13.  * "/board/*" : /board/로 시작하는 요청
  14.  */
  15. public class Front extends HttpServlet {
  16.     private static final long serialVersionUID = 1L;
  17.     private boolean isRedirect = false;
  18.     private String view;
  19.    
  20.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  21.         String contextPath = request.getContextPath();
  22.     //  System.out.println("contextPath:"+contextPath);
  23.         String url = request.getRequestURI();
  24.     //  System.out.println("url:"+url);
  25.         String command = url.substring(contextPath.length());
  26.     //  System.out.println("command:"+command);
  27.        
  28.         if(command.equals("/test/first")){
  29.             this.view = "/view/first_view.jsp";
  30.         }else if(command.equals("/test/second")){
  31.             this.isRedirect = true;
  32.             this.view = "/view/second_view.jsp";
  33.         }
  34.        
  35.         if(this.isRedirect){
  36.             response.sendRedirect(contextPath+view);
  37.         }else{
  38.             request.getRequestDispatcher(view).forward(request, response);
  39.         }
  40.        
  41.     }
  42.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  43.         doGet(request, response);
  44.     }
  45. }
3.first/second_view.jsp
생성


  • FrontController pattern

몇개의 서블릿이 중앙 집중식으로 모든요청을 다 받아서 처리하는 방식
대표적인 Front Controller Pattern : Spring

댓글 없음:

댓글 쓰기