Tomcat in Java

Published in the Random EN group
members
At some point, every developer gains enough skills that he thinks about creating his own project to put his knowledge into practice. It is easiest to take on a web project, since the implementation of a web application is not constrained by any restrictions, such as desktop applications. The client only needs a browser and can interact with the application without downloading any distributions. Without registration and SMS, as they say (although this depends on the application itself). Tomcat in Java - 1So, in order to implement a good web application in Java, you cannot do without a tool called Tomcat. Content:

Tomcat is aware of Javarush

Tomcat is studied at level 9 of the Java Collections quest in the JavaRush course. In 2 lectures, Bilaabo will tell you how to download and configure Tomcat , as well as build your first web application .

Tomcat - what is it?

Tomcat is an open source servlet container that also acts as a web server. At first glance, Tomcat seems like a rather heavy topic, but this is not the case. Most Java applications are launched using the command line and perform some actions. Such applications implement one predefined function, after which they are no longer executed. Such programs usually have a method mainthrough which they can be launched. The web application is designed to interact with the client. If there is a request from the client, it is processed and a response is sent to the user. If not, the application is idle. How to implement such logic in a standard application, given that you need to support sessions, accept HTTP requests, etc.? Cycle while-true? No, we need a reliable solution here. That's what Tomcat is for. In fact, it is a Java application that takes care of opening the port for client interaction, setting up sessions, number of requests, header length and many more operations.

Tomcat Components

Tomcat has components that perform specific functions that are worth knowing about. Let's take a closer look.

Catalina

Thanks to this component, developers have the opportunity to deploy their programs in a container. Catalina implements the Servlet API specification, the core web technology in Java web programming. In fact, Catalina is a servlet container inside Tomcat (we'll look at this concept in more detail below).

Jasper

Thanks to this component, the programmer uses JSP technology. These are like HTML files, only they have embedded Java code that can be executed when the page is sent to the user. This allows you to dynamically embed any data into the page. Jasper turns Java code into HTML, and also tracks changes and automatically updates them.

Coyote

This is an important component that listens for HTTP requests from a client on a specific port, provides that data for processing in the application, and also returns responses to users. That is, Coyote implements the functionality of an HTTP server. These components can be structurally described by the following diagram: Tomcat in Java - 2Here an approximate diagram of the interaction of the components is shown “on the fingers”. In fact, the way Tomcat works is much more complex, but this is enough for a basic understanding.

Installing Tomcat

To use Tomcat in Java, it needs to be installed on the system. You can read about how to install Tomcat in this article, which also covers other application servers. So, having a working Tomcat built into IDEA, you can try to prepare your first servlet.

How to create a web application

To create a web application, you must adhere to a specific folder structure. IntelliJ IDEA has a web application generation function in the project creation menu. Having created the project in this way, you can see a simple structure: Tomcat in Java - 3In src, as always, there are sources, and in the web folder web.xml and index.jsp are generated. web.xml is an instruction for Tomcat where to look for request handlers and other information. index.jsp is the main page of the web application, where the user should go first (this is the default configuration). As a first run, you can simply edit the index.jsp file:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
 <head>
   <title>$Title$</title>
 </head>
 <body>
   <h1>Hello world!</h1>
 </body>
</html>
If Tomcat is installed directly in IDEA, you can start the application server: Tomcat in Java - 4The client receives the contents of the index.jsp file in the browser when it navigates to '/', that is, to the main page. Now let’s add a link to the page where the current server time will be located. To create your first servlet, you need to use the servlet-api.jar library that comes with Tomcat (can be found in the lib folder). Let's create a servlet that will display the current server time on the page. To do this you need to create a class TimeWorker. Let's place it in the src/ru/javarush/tomcat folder:
package ru.javarush.tomcat;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

public class TimeWorker extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     Date date = new Date();
     req.setAttribute("date", date.toString());
     req.getRequestDispatcher("time.jsp").forward(req, resp);
  }
}
TimeWorkerinherits from the class HttpServletand overrides the doGet. In this method we receive two parameters - requestand response. As an example, requestan attribute with a name dataand containing a string representation of the current date is stored. Then it is called and parameters and requestDispatcherare passed to it . The handler has been created. Now you need to send requests specifically to him. Let any transition to lead to the time.jsp page. Open web.xml, insert the following configuration between the tags: requestresponse/time<web-app>
<servlet>
   <servlet-name>timeWorker</servlet-name>
   <servlet-class>ru.javarush.tomcat.TimeWorker</servlet-class>
   </servlet>

<servlet-mapping>
   <servlet-name>timeWorker</servlet-name>
   <url-pattern>/time</url-pattern>
</servlet-mapping>

<welcome-file-list>
   <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
The first tag - servlet- defines the name of the servlet and specifies the path to the servlet class that will process requests. The second tag - servlet-mapping- indicates that the servlet with the name timeWorkerwill be called when a request for url /time. Третий тег — welcome-file-list — указывает файл, который будет вызван при переходе на url /. Это необходимо настраивать, если существует потребность изменить файл по-умолчанию. Здесь включен для примера. Теперь при переходе на /time будет вызываться метод doGet в классе TimeWorker и отдавать page time.jsp… которой нет. Создадим ее рядом с index.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>Hello</title>
</head>
<body>
   <h1>Current server time: <%=request.getAttribute("date")%></h1>
</body>
</html>
Начало классическое, однако в теге h1 идет обращение к an objectу request, которое обрамлено <%= и %>. Это теги шаблонизации. Код, заключенный в данные теги, вызывается до того, How будет отправлен клиенту. Ну а an objectы request и response доступны в таких тегах в любом jsp-файле. В данном примере туда будет подставлено текущее время serverа, которое передает сервлет TimeWorker. В файл index.jsp для удобства создаем ссылку на /time:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
 <head>
   <title>$Title$</title>
 </head>
 <body>
   <h1>Hello world!</h1>
   <a href="/time">Узнать текущее время serverа</a>
 </body>
</html>
Запускаем пример: Tomcat in Java - 5Переходим по ссылке: Tomcat in Java - 6Отлично, все работает. В примере мы реализовали переход с главной pages на вспомогательную, в которую был передан параметр и отображен для пользователя. При наличии проблем с запуском сервлетов рекомендую прочитать этот пост, где дают советы по решению этой проблемы. Для более полного ознакомления с сервлетами, рекомендуем прочитать статьи ( часть 1, часть 2), где автор подробно расписывает создание простейшего applications на сервлетах и jsp.

Как встроить приложение в работающий server

Несмотря на то, что встроенный Tomcat в IDEA — удобная фича, веб-приложение может быть перенесено на другой server и в другой контейнер. Рассмотрим вариант, когда необходимо встроить свое приложение в уже работающий server. Во-первых, необходимо дополнительно разобрать цель и функции контейнера сервлетов. Программа, которая приведена в примере выше — это веб-приложение. Класс TimeWorker — сервлет. Компоненты выполняют исключительно обработку requestов. Данные компоненты должны быть встроены в специальный контейнер сервлетов. Цель контейнера сервлетов — поддержка сервлетов и обеспечение их жизненного цикла. Простейший пример работы Tomcat — сканирование определенной папки с целью определить, появился ли в ней новый сервлет. Если да — инициализировать его и подготовить к приему requestов от клиентов. Если сервлет был обновлен, провести повторную инициализацию для обновления компонентов. При удалении сервлета — остановить обработку requestов, удалить сервлет из Tomcat.

Функции контейнера сервлетов

  1. Обмен данными между сервлетом и клиентами;
  2. Организация клиентских сессий;
  3. Creation программной среды для функционирования сервлета;
  4. Идентификация и авторизация клиентов;
  5. В большинстве случаев — управление метаданными (заголовки, методы и прочее).
Во-вторых, необходимо разобраться, How установить свой сервлет.

Установка сервлета

Tomcat принимает для обработки веб-applications на Java, которые имеют расширение .war. Это How jar, только web. Файлы такого типа объединяют в себе JSP-файлы, сервлеты, class-файлы, статические ресурсы и прочее. При установке такого file в Tomcat происходит его распаковка, а затем запуск, поэтому существует строгое требование к структуре файлов в проекте. Если проект был создан в IDEA, вся структура создана автоматически. Файл war можно создать стандартными средствами IDEA. Для этого необходимо зайти в ProjectStructure -> Artifacts -> Нажать “ +” -> WebApplication: Archive. В открывшемся поле задать Name для итогового war-file, например deployed_war. Ниже необходимо нажать на кнопку Create Manifest… Далее необходимо указать way to папке web проекта. В ней будет создана папка META-INF, в которую будет помещен файл MANIFEST.MF. Далее следует нажать Apply и Ok. Whatбы собрать проект в war-файл, следует во вкладке Build выбрать опцию Build Artifact: Tomcat in Java - 7В появившемся поле нужно нажать на deployed_war. Затем начнется сборка проекта и Intellij IDEA создаст папку out, в которой появится папка artifacts с именем нашего артефакта. В этой папке будет лежать файл deployed_war.war: Tomcat in Java - 8Теперь можно деплоить этот файл в Tomcat. Деплой applications проще всего выполнить из веб-интерфейса Tomcat. Просто нажмите кнопку выбора file на вкладке Deploy, перейдите к местоположению file WAR и выберите его, затем нажмите кнопку развертывания. В обоих случаях, если все пойдет хорошо, консоль Tomcat сообщит нам, что развертывание прошло успешно примерно таким выводом в консоль: INFO: Deployment of web application archive \path\to\deployed_war has finished in 4,833 ms

Польза Tomcat для разработки

Для разработчиков контейнеры сервлетов имеют огромную роль, так How решают целый спектр проблем. Для программирования на Java Tomcat обеспечивает несколько серьезных преимуществ:
  1. Самое главное, Tomcat может выполнять роль полноценного web-serverа. Благодаря этому развертывание приложений происходит гораздо быстрее, чем было раньше.Также Tomcat может выступать в роли классического контейнера сервлетов, который можно встроить в более крупный веб-server.

  2. Tomcat способствует обмену данными между клиентом и сервлетом, обеспечивает программный контекст для веб-приложений, берет на себя функции идентификации и авторизации клиентов, создание сессий для каждого из них.

  3. Предоставляет очень удобное управление JSP-pageми. Фактически веб-server может отдавать только html. Jasper, компонент Tomcat, компorрует code, содержащийся в шаблонных тегах JSP-страниц в корректный HTML-файл, который получает клиент. Вся логика шаблонизации находится внутри Tomcat, позволяя добавлять даже сложные конструкторы в классическую форму HTML.

And finally: very often novice developers are asked the question: is it possible to run a Java application without maina -method. At first glance, if you look at the examples above, it is possible. Our servlet was executed without the main. However, it is not. Tomcat has its own method mainthat is called when the server starts. You can get caught asking this question at an interview.

Additional links:

Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet