JavaRush /Java Blog /Random EN /Part 5. Servlets, Java servlet API. Writing a simple web ...

Part 5. Servlets, Java servlet API. Writing a simple web application

Published in the Random EN group
This material is part of the “Introduction to Enterprise Development” series. Previous articles: Part 5. Servlets, Java servlet API.  Writing a simple web application - 1Do you already know how to write Java applications that output text to the console, but you still don’t really know how to create your first web application? Great, make yourself comfortable. In this article, we will get acquainted with servlets and write an application that you can show off to your friends without sending them a jarnik or forcing them to download Java. Let's write a web application . If you are not yet familiar with the approaches that are used in web programming, I advise you to start reading from the first article in the series “ Introduction to Enterprise Development ”.

What is a servlet

First, let's figure out what a servlet is and why you hear about it so often. Java Servlet API is a standardized API designed for implementation on the server and working with the client using a request-response scheme. A servlet is a class that can receive requests from a client and return responses to it. Yes, servlets in Java are precisely the elements with which the client-server architecture is built. If you remember, we already talked about it in one of the articles in the series. Let's not beat around the bush: let's write some code right away.

What you need to create a web application

To work comfortably with servlets in Java, you will need Intellij IDEA Ultimate Edition. It is paid, but you can activate a 30-day trial period or use the early access version - it is always free. Also install our application server - Apache Tomcat. Tomcat is a servlet container: it is the one that processes incoming requests from the outside and passes them on to our application. You can download Tomcat from this link .

Creating the first web application

If everything is ready, let's create a Maven project. If you are not familiar with Maven, pay attention to the previous article . Let `s start!
  1. In pom.xml, add the javax.servlet-api dependency and set the packaging war:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
       <modelVersion>4.0.0</modelVersion>
    
       <groupId>org.example</groupId>
       <artifactId>servlets</artifactId>
       <version>1.0-SNAPSHOT</version>
       <packaging>war</packaging>
    
       <dependencies>
           <dependency>
               <groupId>javax.servlet</groupId>
               <artifactId>javax.servlet-api</artifactId>
               <version>4.0.1</version>
           </dependency>
       </dependencies>
    </project>

    Simple servlet class:

    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    @WebServlet("/hello")
    public class MainServlet extends HttpServlet {
    
       @Override
       protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           resp.setContentType("text/html");
           PrintWriter printWriter = resp.getWriter();
           printWriter.write("Hello!");
           printWriter.close();
       }
    }
  2. To run the application you need to create a Tomcat configuration:

    Part 5. Servlets, Java servlet API.  Writing a simple web application - 2 Part 5. Servlets, Java servlet API.  Writing a simple web application - 3

  3. Next, we indicate which version of Tomcat we will use, the URL by which we can access the server, and the port. You should get something like this:

    Part 5. Servlets, Java servlet API.  Writing a simple web application - 4
  4. All that remains is to specify the artifact (the assembled project into a jar archive), which will be deployed in the container. You can click the Fix button and select war exploded : this means that after the project is rebuilt, the artifact will be automatically placed in the servlet container. Part 5. Servlets, Java servlet API.  Writing a simple web application - 5

  5. The Application context is set to servlets_war_exploded by default , which means that the application must be accessed at: http://localhost:8080/servlets_war_exploded .

    Why do we need extra text? Let's remove unnecessary things. Now our application address is: http://localhost:8080 .

    Part 5. Servlets, Java servlet API.  Writing a simple web application - 6

  6. Click OK. We see that we now have the opportunity to launch the application:

    Part 5. Servlets, Java servlet API.  Writing a simple web application - 7

    Now, when you launch the application, the browser should open and display a 404 error. This is logical, because at the address http://localhost:8080/ there should be a servlet with the “/” mapping, and our only servlet has the “/hello” mapping .

  7. We contact it at http://localhost:8080/hello and get the expected response - the string “Hello”!

If everything works, let's look at the code. To make an http servlet from a regular class , you need to inherit it from the HttpServlet class. Above the class we specify the @WebServlet() annotation, in which we bind (map) the servlet to a specific path (“/hello”). This annotation appeared only in the Java Servlet API 3.0, so there are a lot of examples on the Internet where servlet mapping occurs through an XML file. Now this is not necessary. To process GET requests , we override the doGet() method. Pay attention to the method arguments - HttpServletRequest and HttpServletResponse. From the HttpServletRequest object we can take all the necessary information about the request, in HttpServletResponse we can record our response and set the necessary headers.

Working with parameters and session

Let's improve our servlet so that it can process request parameters and work with the session:
import javax.servlet.ServletException;
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 ServletException, 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" + "<br>");
       } else {
           printWriter.write("Hello, " + username + "<br>");
       }
       printWriter.write("Page was visited " + visitCounter + " times.");
       printWriter.close();
   }
}
The servlet is currently running the session, incrementing the visitCounter each time the page is visited. If the visitCounter attribute has not yet been created (the first time you visit the page), the getAttribute() method will return null, so you need to check for null. The same applies to request parameters. If the user did not pass the username parameter, its value will be null. In this case, we will greet the user as anonymous. To pass a parameter in a GET request, path-variables are used, that is, you need to access the link http://localhost:8080/hello?username=Pavel . You can read more about http requests in the previous article in the series. Now our application has minimal logic, but the 404 error in the root path is a little annoying. To fix it, let's create another servlet and map it to the initial page @WebServlet("/"). The job of this servlet is to redirect requests to the “/hello” path. There are two ways to do this: using forward or redirect. Perhaps it’s worth understanding what the difference is between them. forward - delegates request processing to another servlet on the server, the client is not involved. To do this, you need to add the following code to the doGet() method of the new servlet:
getServletContext().getRequestDispatcher("/hello").forward(req, resp);
In this code, we access the servlet context, get the request manager of the desired servlet from it and ask it to process a specific request with the specified parameters (req, resp). redirect - returns to the client the address to which he needs to contact to process his request. Most browsers go to the transmitted link automatically. To implement the redirect you need to add this code:
resp.sendRedirect(req.getContextPath() + "/hello");
In HttpServletResponse we call the redirect() method and pass it the address that the client needs to contact. An important detail: http parameters must also be added at the end of the full redirect path, which is not very convenient. In our situation, it is preferable to use forward, but it happens that it is better to use redirect. If you understand the difference in their work, you won’t go wrong with your choice. The code for the new servlet looks like this:
import javax.servlet.ServletException;
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 ServletException, IOException {
//        getServletContext().getRequestDispatcher("/hello").forward(req, resp);
       resp.sendRedirect(req.getContextPath() + "/hello");
   }
}

Bottom line

Your first web application is ready. In the next article you will learn how to deploy it without using Intellij IDEA. We wrote an application that only processes GET requests. The remaining http methods are processed in the same way - overriding the corresponding methods of the parent class. Using such simple servlets, you can build complex, rich web applications. Of course, using large frameworks like Spring, this is much easier to do. But if you really want to delve into all the capabilities of servlets in more detail, you can read the official specification . Part 6. Servlet containers Part 7. Introduction to the MVC (Model-View-Controller) pattern Part 8. Writing a small application in spring-boot
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION