Java Servlet is a server-side program written in the programming language of the same name that receives client signals and sends responses back to it. This is a key element that forms typical Java EE, in addition to JSP, EJB, XML, and other related technologies. An application can be packaged in a WAR (Web AR chive) file for deployment to a web server. A server that can run a Java servlet is called a container. A program that runs on such a server can create dynamic web pages.
Java Servlet: Basics
The most popular and widely used containers are Tomcat and JBoss. Technically, a servlet is a normal Java class that has an extension for a common client-server protocol or HTTP. In practice, it is used to process requests through HttpServlet GET and POST overrides, respectively. The Java Servlet container provides Http.ServletRequest and Http.ServletResponse - objects that work according to the request-response scheme. And commonly used in conjunction with JSP to generate dynamic content.
Typical model scenario:
- JSP presents the user with a form for entering data.
- The servlet receives input, processes it, and sends a response.
- For quality work, he uses special filters.
Java Servlet Filters are Java plug-ins that are used to intercept and process requests before sending them to servlets and responding after the code completes, and before the container sends a response to the client.
Common tasks that are performed with filters:
- Registering request parameters for registering files.
- Authentication and authorization of resource requests.
- Formatting the body of the request or header before sending it to the servlet.
- Compress response data sent to the client.
- Change the response, adding some cookies.
- Java Servlet Header Information.
Filters are connected and configured in the deployment descriptor file (web.xml). Servlets and filters do not know about each other, so you can add or remove a filter by simply editing web.xml. It is allowed to have several filters for one resource or create a chain of filters for web.xml or run Java Servlet filters, implementing the javax.servlet.Filter interface.
Main functions of Servlet
Parallel server requests are processed by threads, which provides important qualities of web multithreading and concurrency.
Main functions:
- Portability. Since Java is platform independent, the same is true for servlets. For example, you can create it in the Windows operating system so that GlassFish developers use it as a web server, and then can run it in any other OS, such as Unix, Linux with the apache Java Servlet web server. This feature makes it portable, and this is its main advantage over CGI.
- Efficiency and scalability. As soon as Servlet is deployed and uploaded to the web server, it can instantly start executing client requests. It is called by a light thread, so several client requests can be filled at the same time using the Java multithreading function. Unlike CGI, where the server initiates a new process for each client request.
- Reliability. Inheriting top Java features such as garbage collection, exception handling, Java security manager and others, it is less prone to management problems and memory leaks. This makes developing the application in it safe and error-free.
The need for dynamic web pages
There are many reasons why a business would like to create dynamic web pages on the fly, for example, when data on a website changes frequently. News and weather sites typically rely on CGI to maintain fresh content that does not require the constant attention of developers. E-commerce web pages that list current prices and inventory levels use CGI to retrieve this content on demand, retrieving it from the company's internal infrastructure.
Many users have experience using Java technology to create CGI-based web services, but Java Servlets are more efficient, more powerful, easier to use, and cheaper than traditional CGI alternatives.
Benefits of Java Servlets:
- Efficiency. In traditional CGI, each HTTP request starts a new CGI process. Even if its code is perfectly implemented, often a significant amount of overhead occurs not only at the start of the process, but also during its execution. When servlets are used, the JVM remains loaded in memory, and each request is processed by a Java thread. As an example, the Java Servlet, if the traditional CGI model has the number of X simultaneous requests, this means that the code for the program is loaded into memory X times. This becomes an excessive load on the web server. However, there are X threads in the servlet environment where only one copy of its class is launched. The result is increased efficiency and scalability across multiple platforms.
- Convenience. When using the program, it makes no sense to learn a new language, for example, Perl, only to perform CGI functions. Servlets also have an extensive infrastructure for many HTML-related tasks, which greatly speeds up the development process.
- Power - unfortunately, traditional CGI scripts leave much to be desired. For example, their usual programs cannot talk directly to web servers, which means that it is necessary to create an entire interface. Servlets can interact directly with web servers, simplifying operations that require direct access to data stores. They are also unique because they can exchange data with other servlets and maintain information between requests, which makes session tracking extremely easy.
- Java portability extends directly to servlets. In fact, almost every main web server currently in use supports Java Servlets directly or through a plug-in.
- Thrift. From a development point of view, implementing servlets is much cheaper than other options that require user-defined coding to work properly with web servers. Java Servlet redirect is ready to go and can maximize business value without sacrificing the benefits of dynamic content.
Creating a directory structure
To get started, create the following directory structure.
Where in the folder:
- Deploy - place the created file.
- Src - Host Java source files in the net.codejava.servlet package.
- WebContent - Store JSP pages and other web resources.
- WebContent \ WEB-INF - the web.xml handle is installed.
- WebContent \ WEB-INF \ - compiled classes.
Next, create a Java source file called QuickServlet.java in the src \ net \ codejava \ servlet directory with the following code.
This servlet calls several methods from the HttpServlet:
- init () - will call the method when it gets access by the first client. Usually, an initialization code is entered here.
- doGet () - triggered every time an HTTP GET request.
The servlet introduces two elements:
- HttpServletRequest - the object wraps all HTTP request headers to gain control over the GET / POST parameters, as well as other HTTP headers sent from clients through the getParameter () and getHeader () methods, respectively.
- HttpServletResponse โ Used to respond to an HTTP request, configure the response headers, and send HTML content back to the user. The doGet () method sends simple HTML code that transmits a message, for example, "Hello, I am a Java servlet!"
Method for implementing client requests:
- DoPost () - called when the user requests an HTTP POST.
- DoGet () - understands Http.ServletRequest and Http.ServletResponse as arguments. In this case, the values โโof the two parameters of the width and height of the rectangle are extracted from the request to calculate the area and send the result back to the client.
- Destroy () - the container will call it when it needs to remove Java, ee Servlet stops.
Writing a JSP Page
Create a file called index.jsp under the WebContent directory with the following contents.
On this JSP page:
- Put a hyperlink with the href = Quick.Servlet attribute, which indicates the relative path of the servlet and the URL mapping for it.
- By clicking on this link, they get an HTTP GET request to the server, and the doGet () method will be called.
- To demonstrate sending an HTTP request, create a simple form with two text fields: width and height.
- The form attribute in action is set to a relative path.
- The Submit button is called Calculate.
The JSP page will look like this.
Announcing and Configuring Java Web Servlet
In order for the servlet to be able to handle user requests, you must declare and configure its mapping in the web descriptor file. Create an XML file with the extension web.xml below the WebContent \ WEB-INF directory with the following XML code.
Obviously, a servlet is declared using an element and its children, indicating a descriptive name for it and specifying the full name of the class. It is configured to serve requests using the element and its child parts, indicating the name declared with the element and the URL pattern that must be mapped to the servlet. A template may be an exact match for a directory.
Compilation
Before compiling, make sure that the PATH environment variable is set, including the JDK_HOME \ bin directory, so that you can access the command line and have an accessible file, which is usually provided by the servlet container.
When using Tomcat, the file is placed in TOMCAT_HOME \ lib and is called. Open the operating system command line utility and change the working directory to QuickServlet, as indicated in the structure. Enter the following command: javac -cp TOMCAT_HOME \ lib \ servlet-api.jar "-d CLASS_DIR SRC_DIR \ QuickServlet.java.
Replace the names TOMCAT.HOME, CLASS_DIR and SRC_DIR with the values: TOMCAT_HOME. This is the installation directory on the computer in the program folder. If the path contains spaces, place it as follows: CLASS_DIR = WebContent \ WEB-INF \ classes SRC_DIR = src \ net \ codejava \ servlet.
This command compiles the QuickServlet.java file and places the generated .class in WebContent \ WEB-INF \ classes.
Web application packaging
The standard way to deploy a Java EE application is to package it with the WAR extension. In the command line enter the command, be sure to indicate the point at the end:
- jarcfvdeploy \ QuickServletApp.war -C WebContent.
The jar program will put everything in a directory in one zip-format archive called Quick.ServletApp.war under the directory. Now deploy the Quick.ServletApp.war file on the server, copy it to the Tomcat directory. Launch the program by running Tomcat 7.exe in the directory. After entering the console, you can see that the Quick.ServletApp.war file is deployed and the server listens on port number 8080.
Testing QuickServletApp
Now they open a web browser and enter the following text into the address bar: HTTP: // local: 8080 / QuickServletApp. Since no specific page is specified, therefore, by default, index.jsp loads on its own.
To check the servlet with the HTTP GET request, click on the "Click here to send a GET request" hyperlink. To check it with an HTTP POST request, click the browser back button and enter two numbers in the width and height of the text fields. Click the "Calculate" button, and it will return the calculated area to the result.
Tomcat Examples
A servlet is a Java web component managed by its container, such as Tomcat, which generates dynamic content in response to a client request. A container or servlet engine is a web server extension that provides servlet functionality. A container maintains and manages servlets throughout its life cycle.
The Servlet interface is a central abstraction of the Java API. HttpServlet - the most common servlet that processes HTTP requests is a subclass of GenericServlet that implements the Servlet interface. The Servlet Interface itself declares these abstract methods.
Servlet lifecycle: voidinit (setting Servlet.Config) voiddestroy () voidservice (Java request Servlet request, response Servlet.Response)
Servlet configuration and information: Servlet.Config getServlet.Config () String getServlet.Info ().
Java Server Features
JSP is another powerful way to create dynamic web content using Java. The easiest way to explain the difference between the two is to recognize that the servlet is HTML in Java and JSP is Java in HTML. Both methods are effective and can be used independently, but there are several differences:
- Servlets typically run faster than JSPs, but JSPs can be compiled into Java servlets.
- A Java web developer should be familiar with both technologies and how they can complement each other in one implementation.
- Many JSP features can be achieved on the client side using JavaScript. This reduces the load on the web server during periods of maximum use and is often the method used for large enterprises with constantly high traffic.
Although stand-alone Java applications peaked some years ago, dynamic Java-based web content is still in high demand by companies around the world.
If the user does not currently use Java Servlets to create dynamic content, he misses an interesting field with unlimited career opportunities.