ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Java] JSP(Java Server Page)란 무엇인가?
    DBProgramming/JSP 2020. 5. 26. 14:49
    728x90
    반응형

    1. JSP(Java Server Page)란?

     JSP는 Java Server Pages 의 약자이며 HTML 코드에 JAVA 코드를 넣어 동적 웹페이지를 생성하는 웹어플리케이션 도구이다. JSP가 실행되면 자바 서블릿(Servlet)으로 변환되며 웹 어플리케이션 서버에서 동작되면서 필요한 기능을 수행하고 그렇게 생성된 데이터를 웹페이지와 함께 클라이언트로 응답한다.

     



    JSP 동작 과정

    • 브라우저가 웹 서버에게 JSP에 대한 요청 정보를 전달한다.
    • 브라우저가 요청한 JSP가 최초로 요청했을 경우만 JSP로 작성된 코드가 서블릿 코드로 변환됨(java파일 생성)
    • 서블릿 코드를 컴파일해서 실행가능한 bytecode로 변환한다(class파일 생성)
    • 서블릿이 실행되어 요청을 처리하고 응답 정보를 생성한다.

     

     

    실제로 .jsp파일을 만들어 실행한 후에 변환된 코드를 찾아보자. (경로는 자신의 Workspace안에서 아래와 같다)

    C:\JDBC_Project\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\ROOT\org\apache\jsp

     

    이렇게 들어가서 변환된 코드를 확인해보자.

     

    /*
     * Generated by the Jasper component of Apache Tomcat
     * Version: Apache Tomcat/8.5.50
     * Generated at: 2020-05-26 04:57:04 UTC
     * Note: The last modified time of this file was set to
     *       the last modified time of the source file after
     *       generation to assist with modification tracking.
     */
    package org.apache.jsp;
    
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.jsp.*;
    
    public final class jspCalCulator_jsp extends org.apache.jasper.runtime.HttpJspBase
        implements org.apache.jasper.runtime.JspSourceDependent,
                     org.apache.jasper.runtime.JspSourceImports {
    
      private static final javax.servlet.jsp.JspFactory _jspxFactory =
              javax.servlet.jsp.JspFactory.getDefaultFactory();
    
      private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;
    
      private static final java.util.Set<java.lang.String> _jspx_imports_packages;
    
      private static final java.util.Set<java.lang.String> _jspx_imports_classes;
    
      static {
        _jspx_imports_packages = new java.util.HashSet<>();
        _jspx_imports_packages.add("javax.servlet");
        _jspx_imports_packages.add("javax.servlet.http");
        _jspx_imports_packages.add("javax.servlet.jsp");
        _jspx_imports_classes = null;
      }
    
      private volatile javax.el.ExpressionFactory _el_expressionfactory;
      private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager;
    
      public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
        return _jspx_dependants;
      }
    
      public java.util.Set<java.lang.String> getPackageImports() {
        return _jspx_imports_packages;
      }
    
      public java.util.Set<java.lang.String> getClassImports() {
        return _jspx_imports_classes;
      }
    
      public javax.el.ExpressionFactory _jsp_getExpressionFactory() {
        if (_el_expressionfactory == null) {
          synchronized (this) {
            if (_el_expressionfactory == null) {
              _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
            }
          }
        }
        return _el_expressionfactory;
      }
    
      public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() {
        if (_jsp_instancemanager == null) {
          synchronized (this) {
            if (_jsp_instancemanager == null) {
              _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
            }
          }
        }
        return _jsp_instancemanager;
      }
    
      public void _jspInit() {
      }
    
      public void _jspDestroy() {
      }
    
      public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
          throws java.io.IOException, javax.servlet.ServletException {
    
        final java.lang.String _jspx_method = request.getMethod();
        if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method) && !javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) {
          response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET POST or HEAD");
          return;
        }
    
        final javax.servlet.jsp.PageContext pageContext;
        javax.servlet.http.HttpSession session = null;
        final javax.servlet.ServletContext application;
        final javax.servlet.ServletConfig config;
        javax.servlet.jsp.JspWriter out = null;
        final java.lang.Object page = this;
        javax.servlet.jsp.JspWriter _jspx_out = null;
        javax.servlet.jsp.PageContext _jspx_page_context = null;
    
    
        try {
          response.setContentType("text/html; charset=UTF-8");
          pageContext = _jspxFactory.getPageContext(this, request, response,
          			null, true, 8192, true);
          _jspx_page_context = pageContext;
          application = pageContext.getServletContext();
          config = pageContext.getServletConfig();
          session = pageContext.getSession();
          out = pageContext.getOut();
          _jspx_out = out;
    
          out.write("\r\n");
          out.write("<!DOCTYPE html>\r\n");
          out.write("<html>\r\n");
          out.write("<head>\r\n");
          out.write("<meta charset=\"UTF-8\">\r\n");
          out.write("<title>Insert title here</title>\r\n");
          out.write("<style>\r\n");
          out.write("input{\r\n");
          out.write("\twidth:50px;\r\n");
          out.write("\theight:50px;\r\n");
          out.write("}\r\n");
          out.write(".output{\r\n");
          out.write("\theight: 50px;\r\n");
          out.write("\tbackground: #e9e9e9;\r\n");
          out.write("\tfont-size:24px;\r\n");
          out.write("\tfont-weight: bold;\r\n");
          out.write("\ttext-align: right;\r\n");
          out.write("\tpadding:0px 5px;\r\n");
          out.write("}\r\n");
          out.write("</style>\r\n");
          out.write("</head>\r\n");
          out.write("<body>\r\n");
          out.write("\r\n");
          out.write("\t<div>\r\n");
          out.write("\t\t<form action = \"calexample.jsp\" method=\"post\">\r\n");
          out.write("\t\t\t<table>\r\n");
          out.write("\t\t\t  <tr>\r\n");
          out.write("\t\t\t  \t<td class=\"output\" colspan=\"4\">");
          out.print( 3 + 4 );
          out.write("</td>\r\n");
          out.write("\t\t\t  </tr>\r\n");
          out.write("\t\t\t  <tr>\r\n");
          out.write("\t\t\t  \t<td><input type=\"submit\" name=\"operator\" value=\"CE\"/></td>\r\n");
          out.write("\t\t\t  \t<td><input type=\"submit\" name=\"operator\" value=\"C\"/></td>\r\n");
          out.write("\t\t\t  \t<td><input type=\"submit\" name=\"operator\" value=\"BS\"/></td>\r\n");
          out.write("\t\t\t  \t<td><input type=\"submit\" name=\"operator\" value=\"/\"/></td>\r\n");
          out.write("\t\t\t  </tr>\r\n");
          out.write("\t\t\t  <tr>\r\n");
          out.write("\t\t\t  \t<td><input type=\"submit\" name=\"value\" value=\"7\"/></td>\r\n");
          out.write("\t\t\t  \t<td><input type=\"submit\" name=\"value\" value=\"8\"/></td>\r\n");
          out.write("\t\t\t  \t<td><input type=\"submit\" name=\"value\" value=\"9\"/></td>\r\n");
          out.write("\t\t\t  \t<td><input type=\"submit\" name=\"operator\" value=\"*\"/></td>\r\n");
          out.write("\t\t\t  </tr>\r\n");
          out.write("\t\t\t  <tr>\r\n");
          out.write("\t\t\t  \t<td><input type=\"submit\" name=\"value\" value=\"4\"/></td>\r\n");
          out.write("\t\t\t  \t<td><input type=\"submit\" name=\"value\" value=\"5\"/></td>\r\n");
          out.write("\t\t\t  \t<td><input type=\"submit\" name=\"value\" value=\"6\"/></td>\r\n");
          out.write("\t\t\t  \t<td><input type=\"submit\" name=\"operator\" value=\"-\"/></td>\r\n");
          out.write("\t\t\t  </tr>\r\n");
          out.write("\t\t\t  <tr>\r\n");
          out.write("\t\t\t  \t<td><input type=\"submit\" name=\"value\" value=\"1\"/></td>\r\n");
          out.write("\t\t\t  \t<td><input type=\"submit\" name=\"value\" value=\"2\"/></td>\r\n");
          out.write("\t\t\t  \t<td><input type=\"submit\" name=\"value\" value=\"3\"/></td>\r\n");
          out.write("\t\t\t  \t<td><input type=\"submit\" name=\"operator\" value=\"+\"/></td>\r\n");
          out.write("\t\t\t  </tr>\r\n");
          out.write("\t\t\t  <tr>\r\n");
          out.write("\t\t\t  \t<td></td>\r\n");
          out.write("\t\t\t  \t<td><input type=\"submit\" name=\"value\" value=\"0\"/></td>\r\n");
          out.write("\t\t\t  \t<td><input type=\"submit\" name=\"dot\" value=\".\"/></td>\r\n");
          out.write("\t\t\t  \t<td><input type=\"submit\" name=\"operator\" value=\"=\"/></td>\r\n");
          out.write("\t\t\t  </tr>\r\n");
          out.write("\t\t\t</table>\t\t\r\n");
          out.write("\t\t\t\r\n");
          out.write("\t\t</form>\r\n");
          out.write("\t</div>\r\n");
          out.write("</body>\r\n");
          out.write("</html>");
        } catch (java.lang.Throwable t) {
          if (!(t instanceof javax.servlet.jsp.SkipPageException)){
            out = _jspx_out;
            if (out != null && out.getBufferSize() != 0)
              try {
                if (response.isCommitted()) {
                  out.flush();
                } else {
                  out.clearBuffer();
                }
              } catch (java.io.IOException e) {}
            if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
            else throw new ServletException(t);
          }
        } finally {
          _jspxFactory.releasePageContext(_jspx_page_context);
        }
      }
    }

    jsp라는 확장자로 서버에 넘겨주면 서버에서 시블럿을 하나 만들어서 동적으로 변환시켜 준 다음에 클라이언트에게 다시 보여주는 것이다. 따라서 out.print()를 노동을 하면서 개발자가 직접 하지 않아도 아파치 톰캣의 Jasper가 변환을 시켜준다. 그리고 위의 _jspService() 메소드는 Servlet에서 Service 메소드와 같다고 생각하면 되고 클라이언트 요청시에 실행되는 메소드라고 기억해두자.

     

     

    그러면 jsp파일은 Java 코드를 쓸 수 있다는데 어떻게 해야 할까?? 

     

     

    JSP 기본 태그

    위의 표는 JSP 기본태그에 대한 설명인데 많이 쓰다보면 외워지기도 하고 표안에 내용을 읽어보면서 의미를 파악하고 많이 써보면서 익혀보면 될 것 같다. 따라서 <% %> 안에 코드를 작성하면 서버에서도 자바코드로 인식을 하게 된다. 

     

     

     

    그리고 query String이 무엇인지 안다고 가정하고 하나 더 정리해보려 한다. 

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    	<%
    		String user = request.getParameter("name");
    		if (user == null) {
    			user = "Guest";
    		}
    	%>
    	
    	<%= user %>
    </body>
    </html>

    엄청 단순한 JSP파일이 있다. 여기서 보면 request.getParameter라는 것을 이용해서 query String의 name이라는 값을 가져와서 String user에 담는 코드이다. 

     

    그러면 request.getParameter는 어떻게 그냥 쓸 수 있는 것일까?? 

       public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
          throws java.io.IOException, javax.servlet.ServletException {
    
        final java.lang.String _jspx_method = request.getMethod();
        if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method) && !javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) {
          response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET POST or HEAD");
          return;
        }
    
        final javax.servlet.jsp.PageContext pageContext;
        javax.servlet.http.HttpSession session = null;
        final javax.servlet.ServletContext application;
        final javax.servlet.ServletConfig config;
        javax.servlet.jsp.JspWriter out = null;
        final java.lang.Object page = this;
        javax.servlet.jsp.JspWriter _jspx_out = null;
        javax.servlet.jsp.PageContext _jspx_page_context = null;
    
    
        try {
          response.setContentType("text/html; charset=UTF-8");
          pageContext = _jspxFactory.getPageContext(this, request, response,
          			null, true, 8192, true);
          _jspx_page_context = pageContext;
          application = pageContext.getServletContext();
          config = pageContext.getServletConfig();
          session = pageContext.getSession();
          out = pageContext.getOut();
          _jspx_out = out;
    
        } catch (java.lang.Throwable t) {
          if (!(t instanceof javax.servlet.jsp.SkipPageException)){
            out = _jspx_out;
            if (out != null && out.getBufferSize() != 0)
              try {
                if (response.isCommitted()) {
                  out.flush();
                } else {
                  out.clearBuffer();
                }
              } catch (java.io.IOException e) {}
            if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
            else throw new ServletException(t);
          }
        } finally {
          _jspxFactory.releasePageContext(_jspx_page_context);
        }
      }

    아까 JSP파일이 Servlet코드로 변환된 것으로 보면 위의 HttpSession, ServletContext등등이 다 선언되어 있는 것을 알 수 있다. 그렇기 때문에 사용할 수 있는 것이다. (동적이 코드이기 때문에 서버에서 처리를 해줄거기 때문이다) 따라서 내장객체이기 때문에 위에 선언되어 있는 것들은 다 사용할 수 있다고 생각하면 된다. 

     

     

    반응형

    댓글

Designed by Tistory.