JavaRush /Java Blog /Random EN /Part 6: Servlet Containers

Part 6: Servlet Containers

Published in the Random EN group
This material is part of the “Introduction to Enterprise Development” series. Previous articles: Part 6. Servlet Containers - 1In the last article, we got acquainted with servlets and learned how to create web applications with their help. It's time to take a closer look at what this holiday wouldn't be possible without - servlet containers.

Content:

What is a servlet container

This is a program that runs on the server and can interact with the servlets we created. In other words, if we want to run our web application on a server, we first deploy a servlet container and then place the servlets in it. The way it works is simple: when a client contacts the server, the container processes his request, determines which servlet should process it and passes it on. Part 6. Servlet Containers - 2

How to use servlet containers

In addition to routing requests, the servlet container performs other functions:
  1. Dynamically generates HTML pages from JSP files.
  2. Encrypts/decrypts HTTPS messages.
  3. Provides restricted access for servlet administration.
In general, it sounds good, all that remains is to figure out how to apply it all. Well, to learn how to use something, you just need... try to use it :) So today we will practice! The most popular servlet container is Apache Tomcat . It is open source and free to use. Download Tomcat for your operating system from this link , and let's see how to work with containers in action.

Installing and running Tomcat

  1. To install Tomcat, simply unpack the downloaded archive into the desired directory.

  2. Please note that Tomcat requires Java version 8 or higher to run. Make sure that the JAVA_HOME environment variable refers to the current jdk version.

  3. Next you need to configure user access to Tomcat . This is done in the tomcat-users.xml file, which is located in the conf folder.

    Tomcat comes pre-provided with four roles:

    • manager-gui - access to the graphical interface and status page;
    • manager-script - access to the text interface and status page;
    • manager-jmx - access to JMX and status page;
    • manager-status - access only to the status page.

    Inside the <tomcat-users> tag, we will explicitly write these roles and assign them to our user:

    <role rolename="manager-gui"/>
    <role rolename="manager-script"/>
    <role rolename="manager-jmx"/>
    <role rolename="manager-status"/>
    <user username="user" password="password"
        roles="manager-gui, manager-script, manager-jmx, manager-status"/>

    Now everything is ready to launch!

  4. In the bin folder, run the startup.bat file (startup.sh on Linux).

  5. After a few seconds, open the link http://localhost:8080/ in your browser . The graphic manager will appear there:

    Part 6: Servlet Containers - 3

    If you see such a menu, it means Tomcat is running.

  6. If it doesn't work, manually check the JAVA_HOME and CATALINA_HOME environment variables:

    • JAVA_HOME - must refer to the current version of Java 8+;
    • CATALINA_HOME - must refer to Tomcat or be absent (must not point to another version of Tomcat).

Deploying an Application to Tomcat

We managed to launch Tomcat, so it’s time to deploy some kind of project in it. Let's use the servlets from the previous article . MainServlet:
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/hello")
public class MainServlet extends HttpServlet {

   @Override
   protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
       HttpSession session = req.getSession();
       Integer visitCounter = (Integer) session.getAttribute("visitCounter");
       if (visitCounter == null) {
           visitCounter = 1;
       } else {
           visitCounter++;
       }
       session.setAttribute("visitCounter", visitCounter);
       String username = req.getParameter("username");
       resp.setContentType("text/html");
       PrintWriter printWriter = resp.getWriter();
       if (username == null) {
           printWriter.write("Hello, Anonymous" + "
"
); } else { printWriter.write("Hello, " + username + "
"
); } printWriter.write("Page was visited " + visitCounter + " times."); printWriter.close(); } }
IndexServlet:
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/")
public class IndexServlet extends HttpServlet {

   @Override
   protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
       resp.sendRedirect(req.getContextPath() + "/hello");
   }
}
Before deployment, our servlets must be packaged in a war archive. Usually Maven is used for this, but to create a war archive you need a web.xml file in which all servlets are mapped. We wrote servlets using the new @WebServlet annotation, so we don’t have web.xml. Fortunately, IDEA can do the dirty work for us and wrap our project individually in a war archive. To do this, you need to open the project structure (Ctrl + Shift + Alt + S) -> Artifacts -> Select the desired build -> Check the box next to “Include in project build” -> Click “OK”. Part 6: Servlet Containers - 4Build a project using the combination Ctrl + F9. Now our war archive is in the target directory. Part 6: Servlet Containers - 5The file can be renamed something simpler - for example, servlet.war - and moved to a more convenient place - in C:\my\. When the brew is ready to use, place it in a container . This can be done in two ways.
  1. Via GUI

    To do this, follow the link http://localhost:8080/manager/html . Tomcat should prompt you for a login and password.

    If you repeated all the steps after me, then the login is user, the password is password .

    After successful authorization you will see Tomcat Web Application Manager. The Applications section already contains 5 applications - these are Tomcat utility applications necessary to simplify working with it. They can be removed in the future.

    Part 6: Servlet Containers - 6

    Below is the Deploy section. Using it, you can select a war archive for deployment. Let's enter the path and context manually:

    Part 6. Servlet Containers - 7

    Click “Deploy”, we see that our application has appeared in the Applications section:

    Part 6: Servlet Containers - 8 Using the Tomcat GUI we can stop it, restart it, set the session length and delete it. When deploying, we specified the context /demo, which means that our application must be accessed via the link http://localhost:8080/demo . Check, everything should work.

  2. Through the file system

    To deploy an application in this way, you need to open the directory in which Tomcat is unzipped and go to webapps. Here are the utility applications we are familiar with:

    Part 6: Servlet Containers - 9

    All we need to do is move our servlet.war here.

    We wait a few seconds, we see that a new servlet folder has appeared, which means that our application is deployed. Let's go to the familiar Application Manager interface - http://localhost:8080/manager/ . Here we see that our application is deployed in the /servlet context:

    Part 6: Servlet Containers - 10

    When deployed in this way, the context is automatically assigned to the name of the deployed war archive. To change the context, you can rename the newly created folder with the application, but before that you need to delete the file: otherwise Tomcat will redeploy the application with the name of the archive.

    As you can see, deploying applications to Tomcat is much easier than it might seem. But its other functions are easy to use. Let's check.

Using HTTPS protocol instead of HTTP

If you remember, we discussed the difference between HTTP and HTTPS in a separate article . HTTPS is the same protocol as HTTP, but uses encryption of the data that is transferred. On the client side, encryption is handled by the browser, and we must provide encryption on the server side. Since HTTP requests are accepted and routed by Tomcat, it would be logical to delegate encryption to it. To do this you need:
  1. Generate a self-signed certificate;
  2. Make additional server settings.
Let's practice this.

Generating a certificate

The JDK comes with a large number of utilities, regardless of version, one of which is keytool . This is a tool for generating encryption keys and working with them. To use it, using the command line, go to the C:\Program Files\Java\jdk1.8.0_181\bin directory and run the command keytool -genkey -alias tomcat -keyalg RSA .
  • keytool - launch the utility with parameters;
  • -genkey - indicate that we want to generate a new key;
  • -alias tomcat — create a key alias;
  • -keyalg RSA - select RSA as the key generation algorithm.
After executing the command, the utility will start a dialogue with us: Part 6: Servlet Containers - 11Enter the necessary information. Now we have created a keystore in our home directory (for Windows it is C:\Users\{username}\.keystore) and a tomcat key in it. We have generated a simple certificate that most browsers will accept. This certificate is not suitable for commercial applications: it can only be used for testing purposes. On the production server, you must use a certificate from a certificate authority (for example, https://letsencrypt.org/ ).

Setting up the server

Now that the certificate is ready, you need to adjust the server settings, namely the SSL connector. This is done in the server.xml file, which is located in apache-tomcat-9.0.30/conf/ . We find blocks like:
<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" SSLEnabled="true">
        <SSLHostConfig>
            <Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
                         type="RSA" />
        </SSLHostConfig>
 </Connector>
and place our configuration next to them:
<Connector
       protocol="org.apache.coyote.http11.Http11NioProtocol"
       port="8443" maxThreads="200"
       scheme="https" secure="true" SSLEnabled="true"
       keystoreFile="C:\Users\user\.keystore" keystorePass="mypass"
       clientAuth="false" sslProtocol="TLS"/>
We assign the keystoreFile and keystorePass parameters the values ​​that are relevant for us, save and restart Tomcat using the shutdown.bat and startup.bat files. Now the server is ready to process https requests, just a little at the changed address - https://localhost:8443/demo/hello . When you click on the link, you will see a warning about the certificate being questionable, which is not surprising. As described a little earlier, to obtain a normal certificate you need to use the services of one of the certification services. But so far we have achieved our goal: the application works using the HTTPS protocol, and this is the main thing!

Dynamic generation of HTML pages

Now let's continue our review of other features of servlet containers - dynamic generation of HTML pages. Imagine an ideal world where, instead of boring static HTML code, you could write JAVA code using variables, loops, arrays and other language constructs. Did you imagine? The good news is that something similar exists, the bad news is that it doesn’t fully exist. If you haven't guessed, we are talking about JSP (Java Server Pages) technology. In short, this is a technology that allows you to insert pieces of JAVA code into an HTML page. True, then this code is still turned into HTML before being sent to the client, but it will be dynamically generated taking into account various factors. For example, you can use conditional constructions and serve different content depending on some condition. Example JSP page:
<%@ page language="java"" %>
<html>
<head>
<title>JSP</title>
</head>

<body>
<%
String firstName="name";
String secondName="surname";

    if(firstName.equals("name")){
      out.print("Hello :"+firstName+"<br>");
    }

    if(firstName.equals("name") && secondName.equals("surname"))
    {
      out.print("Hello, my dear friend! <br>");
    }
    else
    {
      out.print("I don’t know you. Go away! <br>");
    }
%>
</body>
</html>
You can read more about JSP here . Actually... we are not here for this, but for the sake of servlet containers! What does JSP have to do with it? It's simple: the transformation of JAVA code from JSP into HTML code is carried out by the servlet container. When a servlet is about to return JSP content as a response, the container takes notice and first turns it into a browser-readable HTML page before sending that content to the client. Today there are many analogues of JSP technology - Thymeleaf, FreeMarket, Mustache and others. They all work on a similar principle. Which one to choose for work is a matter of taste. This also applies to choosing a servlet container. In the examples we used Tomcat, the most common container, but some projects use others. It’s worth briefly familiarizing yourself with the most popular ones and looking at their differences from Tomcat.

Alternatives to Tomcat

  1. GlassFish is an open source container supported by Oracle.

    Unlike Tomcat, it is a full-fledged web server that, in addition to servlets, can operate other components from the JavaEE framework. At the same time, it uses a lot more RAM. More flexible when fine-tuning the server, which makes it more difficult to use. It is worth using when developing applications using the JavaEE framework.

  2. WildFly - formerly Jboss . Also open source. Developed by Red Hat. The name was changed to avoid confusion with another company product - JBoss Enterprise Application Platform.

    WildFly, like GlassFish, is a full-fledged web server. By the way, under the hood WildFly uses Tomcat as a servlet container. Unlike GlassFish, WildFly is more lightweight and easier to set up.

  3. Jetty - similar to the previous ones, is open source. Developed by Eclipse.

    Like Tomcat, it is a simple servlet container, without support for all the components of the JavaEE framework. At the same time, it is more lightweight and can be run even on a mobile phone. It starts and stops quickly and scales well. Unlike Tomcat, it has a smaller community and knowledge base.

  4. WebLogic is licensed software that requires purchase before use. Owned by Oracle.

    Compared to Tomcat, its functionality is a little wider. Can work with the ftp protocol. But it is not so flexible when developing and testing applications.

  5. WebSphere (WebSphere Application Server to be precise) is a paid software. Developed by IBM. Similar to WildFly and GlassFish, it is a full-fledged application server. But it has a friendlier setup interface, plus high operational reliability.

    The downside is that it uses a lot of resources, takes a long time to start and stop, which is not very convenient when developing small projects.

Which servlet container or application server to choose depends on the specific project. There are projects where even an obvious outsider will be able to prove himself to the highest quality, but at first it is better to thoroughly understand one thing. Probably the ideal candidate for this one is Tomcat. We have already taken the first steps in studying it, and then it’s up to you! In the final articles of the “Introduction to Enterprise Development” series, we will get acquainted with the MVC pattern. Part 7. Introduction to the MVC pattern (Model-View-Controller) Part 8. Writing a small application in spring-boot
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION