개발 무지렁이

[Servlet] 클라이언트, 톰캣(Tomcat), DispatcherServlet으로 이어지는 HTTP 요청처리 본문

Backend/Servlet & JSP

[Servlet] 클라이언트, 톰캣(Tomcat), DispatcherServlet으로 이어지는 HTTP 요청처리

Gaejirang-e 2023. 8. 20. 15:10

𐂂 아파치(Apache) 톰캣(Tomcat)은 WAS 서버의 한 종류이다.
서블릿(Servlet), JSP 등을 실행하는데 사용되는 서블릿 컨테이너(Servlet Container)구현체이다.
클라이언트로부터 오는 HTTP 요청을 처리하고, 웹 컴포넌트로 전달하며,
웹 애플리케이션의 배포를 담당하고 있다.

🧸 컴포넌트(Component)
: 웹 애플리케이션작은 조각으로 분리하여, 구성하는 방법을 나타내는 개념으로써
재사용한 독립적인 기능을 가진 작은 모듈을 뜻한다.

📕 참고 자료 📕
Tistory's Card


톰캣(Tomacat)HTTP Request파싱하여,
이 내용을 HttpServletRequest 객체변환하여 제공한다.

🧸 파싱(parsing) 이란
구문을 분석하여, 의미구조를 이해하는 과정을 말한다.

𖠃 DispatcherServlet

📜 DispatcherServlet.java

  @WebServlet({"/DispathcerServlet", "/dispatcher", "*.bit"}) //여러개의 url 매핑 설정, .bit로 끝나는 요청url에도 매핑
  public class DispatcherServlet extends HttpServlet {
       private static final long serialVersionUID = 1L;
    private Logger work_log = Logger.getLogger("work");

    public DispatcherServlet() {
        super();
    }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String uri = request.getRequestURI();
        request.setCharacterEncoding("UTF-8");
        String path = uri.substring(uri.lastIndexOf("/"));
        work_log.debug(path);

        path = path.substring(1, path.lastIndexOf("."));
        work_log.debug(path);

        //주어진 path가 없으면 index으로 이동
        String next = "index.jsp";
        if(path != null) {
            next = path; //주어진 path가 있으면 그 path로 이동
        }
          //기존의 request, response를 유지하면서 페이지를 이동하는 방법(정보유지)  
        RequestDispatcher rd = request.getRequestDispatcher(next);
        rd.forward(request, response);
    }
  }

📜 MainServlet.java

  public class MainSevlet extends HttpServlet {
      private static final long serialVersionUID = 1L;
      private Logger user_log = Logger.getLogger("user");
      ServiceFrame<String, Cust> custService;

      public MainServlet() {
          super();
          custService = new CustServiceImpl();
      }

      protected void service(HttpServletRequest request, HttpServletResponse response throws ServletException, IOException {
          String next = "index.jsp";
          String view = request.getParameter("cmd");

          if(cmd != null) {
              build(request, cmd);
          }
      }

      private void build(HttpServletRequest request, String cmd) {
          if(cmd.equals("register")) {
              request.setAttribute("center", "register");
          } else if(cmd.equals("map")) {
              request.setAttribute("center", "map/map");
          } else if(cmd.equals("chart")) {
              request.setAttribute("center", "chart/chart");
          } else if(cmd.equals("login")) {
              request.setAttribute("center", "login");
          } else if(cmd.equals("loginImpl")) {
              String id = request.getParameter("id");
              String pwd = request.getParameter("pwd");
              Cust cust = null;
              try {
                  cust = custService.get(id);
                  if(cust.getPwd().equals(pwd)) {
                      user_log.debug(cust.getId());
                      HttpSession session = request.getSession();
                      session.setAttribute("logincust", cust);
                  } else {
                      throw new Exception();
                  }    
              } catch(Exception e) {
                  request.setAttribute("center", "loginerror");
                  e.printStackTrace();
              }
          } else if(cmd.equals("logout")) {
              HttpSession session = request.getSession();
              if(session != null) {
                  session.invalidate();
              }    
          }    
      }
  }

📜 index.jsp

  <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
  <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
  <!DOCTYPE html>
  <html lang="en">
  <head>
    <title>Bootstrap 4 Website Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.4/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>

    <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
    <style>
    .fakeimg {
      height: 200px;
      background: #aaa;
    }
    </style>
  </head>
  <body>
    <ul class="nav justify-content-end">
      <c:choose>
        <c:when test="${logincust == null}">
          <li class="nav-item">
            <a class="nav-link text-body" href="main.bit?cmd=login">LOGIN</a>
          </li>
          <li class="nav-item">
            <a class="nav-link text-body" href="main.bit?cmd=register">REGISTER</a>
          </li>
        </c:when>
        <c:otherwise>
          <li class="nav-item text-body">
            <a class="nav-link text-body" href="#">${logincust.id}</a>
          </li>
          <li class="nav-item">
            <a class="nav-link text-body" href="main.bit?cmd=logout">LOGOUT</a>
          </li>
        </c:otherwise>
      </c:choose>
    </ul>

    <div class="jumbotron text-center" style="margin-bottom:0">
      <h1>HTML5 & JSP</h1>
    </div>

    <nav class="navbar navbar-expand-sm bg-dark navbar-dark">
      <a class="navbar-brand" href="main.bit">HOME</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
        <span class="navbar-toggler-icon"></span>
      </button>

      <div class="collapse navbar-collapse" id="collapsibleNavbar">
        <ul class="navbar-nav">
          <li class="nav-item">
            <a class="nav-link" href="js.bit?cmd=js1">JS1</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="js.bit?cmd=js2">JS2</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="main.bit?cmd=map">Map</a>
          </li>   
          <li class="nav-item ">
            <a class="nav-link" href="main.bit?cmd=chart">Chart</a>
          </li>
          <li class="nav-item ">
            <a class="nav-link" href="item.bit?cmd=register">Upload</a>
          </li>     
        </ul>
      </div>
    </nav>
    <c:choose>
      <c:when test="${center != null}">
        <jsp:include page="${center}.jsp" />
      </c:when>
      <c:otherwise>
        <jsp:include page="center.jsp" />
      </c:otherwise>
    </c:choose>
    <div class="jumbotron text-center" style="margin-bottom:0">
      <p>Footer</p>
    </div>
  </body>
  </html>

📕 참고 자료 📕
Tistory's Card

Comments