본문 바로가기

개발기술/Web Dev

톰캣을 통한 JSP 사용법

배경 

아파치 톰캣을 설정하여 JSP를 통해 웹페이지를 구현하는 방식은 현재 시점에서 상당히 오래된 기술이다. 학원 측에서는, 과거의 기술을 하나씩 경험하면서 최신기술을 배워나가길 바라는 모양이다. 

 

강의 내에서는 Eclipse를 통해서 환경설정을 하였는데, Intellij를 선호하는 하는 만큼, 그리고 개발자는 스스로 탐색하여 배우고 문제를 해결해 나갈 수 있어야한다는 말처럼 구글링을 통해 시행착오를 거치면서 환경설정을 해보고자한다.

 

아파치 톰캣 설정

  • 아파치 톰캣 홈페이지에서 톰캣9의 tar.gz파일을 다운로드 받아서 CLI를 통해 bin폴더 startup shell파일을 command(./startup)명령어로 실행할 수 있다.  http://localhost:8080/으로 접속시에 local에서 호스트하는 서버페이지로 접속할 수 있다. webapps의 root - index.html 파일이 호스트서버의 페이지문서이다.단, 본내용은 참고용이고 template이나 framework를 사용하면 직접 CLI를 사용할 필요 없다. 
  • JSP :  Java를 이용한 서버 사이드 템플릿 엔진이다. jsp 는 자바를 웹서버에서 쉽게 쓰기 위한 기술이며 언어가 아니다.동적인 java와 정적인 html을 융합시킨파일로 <%, %> 해당 꺽쇠 안의 내용은 동적인 내용이 표시된다. 이 JSP 파일을 Servlet 자바소스로 클래스로 변환하고 컴파일 역할을 하는 프로그램을 JSP 컨테이너라 하며 컴파일된 서블릿 클래스 파일을 실제로 실행하는 프로그램은 서블릿 컨테이너 혹은 웹 컨테이너라고 부른다.. 대표적인 것으로 Tomcat
  • 해당 과정을 세부적으로 뜯어보면, jsp파일은 우선 java파일로 변환되어 필요한 클래스와 패키지를 호출과 상속한다. 그리고 out개체 안의 string을 html 양식과 함께 write method로 한줄 한줄 작성을 한다. 그리고 배포에 필요한 세션 등 웹 프로토콜에 대한 설정을 java file내에서 완료하고 이를 자동으로 컴파일한다. 

JAVA EE Webproject 생성

  • new project를 생성시 왼쪽 패널에서 1. Generator - Jakarta EE 선택 2. 다운로드 받은 톰캣 tar.gz파일을 unzip해서 해당 디렉토리를 선택함 3. web application 을 선택함 4.  Next를 눌러서 version선택에서 java EE 8 을 선택 ( 톰캣 9부터 jakarta를 지원) 5.  specifications에서 fullplatform을 선택함 5. project create
 

Dynamic Web project Setting (Jakarta template) 

- WEB Project이므로 Java프로젝트와 달리 .java 외에  다양한 파일들이 존재한다. Main에 Java폴더와 webapp이라는 폴더가 존재하며 그 외 여러가지 서버동작을 위한 설정값이 들어있는 xml파일이 존재한다. 

- java파일에는 java로 작성된 비즈니스 로직이 들어가있고, webapp에는 user가 web에 접속하였을때의 홈 directory가 된다. 

- java 파일의 로직을 보관하고 instance 형태로 로직을 webapp에 끌어와서 결과로 출력하는 방식으로 역할을 분담시킨다.

- jdbc같은 lib를 사용하는 instance가 webapp에서 사용된다면, jdbc를 포함하는 lib폴더가 webapp의 web-inf 아래에도 lib폴더를 넣어줘야 로직이 작동함.(프로젝트 구조의 라이브러리 경로에 jar파일을 등록하는 것도 필요함)

 

Tomcat JSP 사용법

Element Dynamic Generation

  • JSP는 동적인 java와 정적인 html을 융합시킨파일로 <%, %> 해당 꺽쇠 안의 내용은 동적인 Java의 코드가 들어간다. 
  • <%=logic%> : out.write대신 html문서에 값을 표시함, 이를 통해서 html을 기본 골격으로 하되, 필요한 부분만 동적으로 변경하는 방식으로 구성.
    • out.println 이라는 객체 메소드를 통해서 html 텍스트를 입력할 수 있다.
    • out.write("text"") : jsp에서 사용하는 out이라는 개체를 통해서 html 문서에 text를 add하게된다. System.out.println("text")는 웹페이지가 아니라 단순히, 콘솔에 text를 출력한다

Handling Requests and Responses

In a JSP, you don't need to explicitly create HttpServletRequest and HttpServletResponse objects as you would in a servlet. These are provided as implicit objects

 

1. Getmethod using query parameter

  • http주소를 생성하여 hyper-link를 만들때 일반적으로 get method를 사용하게 되는데, 이때 uri주소 외에도 parameter을 추가적으로 보낼 수 있다. uri주소 뒤 ?parameter1=value1&paramter2=value2 와 같은 형식으로 전달된다. 
<a href = "detail.jsp?userID=<%=member.getEmail()%>">
  • Query parameter do not affect the location of the webpage itself. They primarily serve to transmit additional information to the server that can be used to modify the content or behavior of the page
  • 해당 parameter value는 서블릿을 통해서 parsing되고 서블릿의  request 객체를 통해서 추출하여 웹페이지 컨텐츠의 동적생성에 사용된다.

2. Getmethod using JSON body

 

그 외 학습개념정리

 

- Jakarta EE is not a framework in the traditional sense but a specification or a collection of specifications for enterprise Java applications. It defines a set of APIs and provides the standards that need to be implemented by an application server. This makes Jakarta EE more about establishing guidelines for compliant application development rather than being a framework itself.

- 마치 자바에서의 인터페이스처럼, 구체적인 구현방법은 지정하지 않지만 필요한 method들은 지정하는 셈이라고 할 수 있다.

 

- Spring Framework, on the other hand, is a true framework. It provides a comprehensive programming and configuration model with actual implementations and libraries that developers directly integrate into their applications.

 

- Deployment : deployment refers to the process of taking your developed application and making it accessible to users in a production environment. When you deploy your Java EE application to Tomcat, it performs a crucial step called JSP compilation. Tomcat treats compiled JSPs as servlets behind the scenes. It loads the compiled class file and creates a servlet instance based on it. When a user requests a URL that maps to a JSP (e.g., /index.jsp), Tomcat uses the servlet instance created from the compiled JSP to handle the request and create response.

 

출처

- velog ; https://velog.io/@getbrave/Intellij-Tomcat

- IntelliJ IDEA Ultimate의 Tomcat  ; https://www.youtube.com/watch?v=ThBw3WBTw9Q 

 

참고할만한 자료

- 톰캣 공식문서 https://tomcat.apache.org/tomcat-9.0-doc/index.html

- Intellij 톰캣 환경설정 https://www.jetbrains.com/help/idea/run-debug-configuration-tomcat-server.html