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!-
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(); } }
-
To run the application you need to create a Tomcat configuration:
-
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:
-
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.
-
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 .
-
Click OK. We see that we now have the opportunity to launch the application:
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 .
-
We contact it at http://localhost:8080/hello and get the expected response - the string “Hello”!
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");
}
}
GO TO FULL VERSION