At some point, every developer gains enough skills, and he has the idea of ​​​​creating his own project in order to put the 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 aware of Javarush

Tomcat is learned at level 9 of the Java Collections quest in the CodeGym 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 heavy topic, but it's not. Most Java applications run from the command line and do some things. Such applications implement one predefined function, after which they are no longer executed. Such programs, as a rule, 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 maintain sessions, accept HTTP requests, and so on? Cyclewhile-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 a 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 and 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, a core web technology in Java web programming. In fact, Catalina is a servlet container inside Tomcat (more on this concept below).

Jasper

Thanks to this component, the programmer uses JSP technology. They 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 the client on a specific port, provides this 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, “on the fingers”, an approximate diagram of the interaction of components is shown. In fact, the scheme of how Tomcat works is much more complicated, but this is enough for a basic understanding.

Installing Tomcat

To use Tomcat in Java, it must be installed on the system. You can read about how to install Tomcat in this article, which also covers other application servers. So, with 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 follow a specific folder structure. IntelliJ IDEA has a web application generation option 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 - the main page of the web application, where the user should get first of all (we are talking about 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. And 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/codegym/tomcat folder:
package ru.codegym.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);
  }
}
TimeWorkerinherited 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 in. Then it is called and parameters and requestDispatcherare passed to it . The handler has been created. Now you need to send requests to him. Let any navigation through 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.codegym.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 handle requests. The second tag - servlet-mapping- indicates that the servlet with the name timeWorkerwill be called when a request is received for url /time. The third tag - - indicates the file that will be called when switching to . This must be configured if there is a need to change the default file. It's included here for an example. Now, when switching to, a method in the class will be called and give the time.jsp page ... which does not exist. Let's create it next to index.jsp: welcome-file-list url / /time doGet TimeWorker
<%@ 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>
The beginning is classic, but the tag h1refers to the object request, which is framed by <%=and %>. These are template tags. The code enclosed in these tags is called before it is sent to the client. Well, objects requestare responseavailable in such tags in any jsp file. In this example, the current time of the server, which is transmitted by the servlet, will be substituted there TimeWorker. In the index.jsp file, for convenience, we create a link to /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>
Let's run the example: Tomcat in Java - 5Follow the link: Tomcat in Java - 6Great, everything works. In the example, we implemented the transition from the main page to the auxiliary one, to which the parameter was passed and displayed to the user. If you have problems with running servlets, I recommend reading this post , where they give tips on solving this problem. For a more complete acquaintance with servlets, we recommend reading the articles ( part 1 , part 2 ), where the author describes in detail the creation of a simple application on servlets and jsp.

How to embed an application on a running server

Even though the built-in Tomcat in IDEA is a nice feature, the web application can be moved to another server and into another container. Consider the option when you need to embed your application into an already running server. First, you need to further parse the purpose and functions of the servlet container . The program shown in the example above is a web application. The class TimeWorkeris a servlet. Components only handle request processing. These components must be embedded in a special servlet container. Purpose of a Servlet Container- Support for servlets and ensuring their life cycle. The simplest example of how Tomcat works is scanning a specific folder to see if a new servlet has appeared in it. If so, initialize it and prepare it to receive requests from clients. If the servlet has been updated, reinitialize to update the components. When removing a servlet, stop processing requests, remove the servlet from Tomcat.

Servlet Container Functions

  1. Data exchange between servlet and clients;
  2. Organization of client sessions;
  3. Creation of a software environment for the functioning of a servlet;
  4. Identification and authorization of clients;
  5. In most cases, metadata management (headers, methods, etc.).
Second, you need to figure out how to install your servlet .

Servlet installation

Tomcat accepts Java web applications that have a .war extension for processing. It's like jar, only web. These types of files combine JSP files, servlets, class files, static resources, and more. When such a file is installed in Tomcat, it is uncompressed and then run, so there is a strict requirement for the file structure in the project. If the project was created in IDEA, the entire structure is created automatically. The war file can be created using standard IDEA tools. To do this, go to ProjectStructure -> Artifacts -> Press “ + ” -> WebApplication: Archive . In the field that opens, specify a name for the final war file, for example, deployed_war. Below you need to click on the button Create Manifest ... Next, you need to specify the path to the web folder of the project. A META-INF folder will be created in it, in which the MANIFEST.MF file will be placed. Next, click Apply and Ok . To compile the project into a war file, select the Build Artifact option in the Build tab : In the field that appears, click on deployed_war . Then the build of the project will start and Intellij IDEA will create an out folder, which will contain an artifacts folder with the name of our artifact. This folder will contain the deployed_war.war file: Now you can deploy this file to Tomcat. The easiest way to deploy an application is from the Tomcat web interface. Just click the file select button Tomcat in Java - 7 Tomcat in Java - 8 on the Deploy tab, navigate to the location of the WAR file and select it, then click the deploy button . In both cases, if everything goes well, the Tomcat console will tell us that the deployment was successful with something like this console output: INFO: Deployment of web application archive \path\to\deployed_war has finished in 4,833 ms

Benefits of Tomcat for Development

For developers, servlet containers play a huge role as they solve a wide range of problems. For Java programming, Tomcat provides several major advantages:
  1. Most importantly, Tomcat can act as a complete web server. This makes application deployment much faster than it used to be. Tomcat can also act as a classic servlet container that can be embedded in a larger web server.

  2. Tomcat facilitates the exchange of data between the client and the servlet, provides a programming context for web applications, takes on the functions of identifying and authorizing clients, creating sessions for each of them.

  3. Provides a very convenient management of JSP pages. In fact, the web server can only serve html. Jasper, a Tomcat component, compiles the code contained in JSP page template tags into a valid HTML file that the client receives. All templating logic resides inside Tomcat, allowing you to add even complex constructors to a classic HTML form.

And finally: very often, novice developers are asked the question: is it possible to run a Java application without mainthe -method. At first glance, if you look at the examples above, you can. Our servlet was executed without a main. However, it is not. Tomcat has its own method main, which is called when the server starts. This question can come up in an interview.

Additional links: