- Written by Nam Ha Minh
- Last Updated on 11 March 2020 Print Email
1. A brief overview of Java servletA servlet is a server-side component written in Java programming language that receives requests from client and sends responses back.Servlet is the key component that forms a typical Java EE application, beside JSP, EJB, XML and other related technologies. A Java EE application can be packaged in a WAR file (W
Apache Tomcat ® is an open source software implementation of a subset of the Jakarta EE (formally Java EE) technologies. Different versions of Apache Tomcat are available for different versions of the specifications. The mapping between the specifications and the respective Apache Tomcat versions is. The aim of the tool is to take a web application written for Java EE 8 that runs on Apache Tomcat 9 and convert it automatically so it runs on Apache Tomcat 10 which implements Jakarta EE 9. The tool can be used from the command line or as an Ant task. Users of Tomcat 10 onwards should be aware that, as a result of the move from Java EE to Jakarta EE as part of the transfer of Java EE to the Eclipse Foundation, the primary package for all implemented APIs has changed from javax. to jakarta. Apache Tomcat (or simply Tomcat) is an open source web server and Servlet container developed by the Apache Software Foundation (ASF). Tomcat implements the Java Servlet and the JavaServer Pages (JSP) specifications. This can be managed manually or configured in any IDE. Want all of our free Java training videos? Visit our Learning Library, which features all of our training courses and tutorials at http://learn.infiniteskill.eb ARchive) in order to be deployed on a web server. A web server that can run Java servlet is called a servlet container. The most popular and widely used servlet containers are Apache Tomcat, Glassfish, JBoss, etc.Technically, a servlet is a normal Java class that extends either:
- javax.servlet.GenericServletclass for generic client-server protocol, or:
- javax.servlet.http.HttpServlet class for HTTP protocol.
Tomcat Java Ee Application Server’s doGet(), doPost() methods to handle GET and POST requests, respectively. The servlet container supplies an HttpServletRequest object and an HttpServletResponse object for dealing with the request and response.Servlet is usually used in conjunction with JSP for generating dynamic content based on client’s requests. A typical scenario would be:
- The JSP presents a form to user for inputting data.
- The servlet receives user’s inputs, processes it and sends response back.
2. Creating directory structure
Java Ee Tomcat TutorialTo get started, create the following directory structure:
- deploy: we will put generated war file here.
- src: contains Java source files in the package net.codejava.servlet.
- WebContent: contains JSP pages and other web resources.
- WebContentWEB-INF: we will put web deployment descriptor file (web.xml) here.
- WebContentWEB-INFclasses: we will put compiled classes here.a
Create a Java source file called QuickServlet.java under the directory srcnetcodejavaservlet with the following code:This servlet overrides four methods from the HttpServlet class:
3. Coding the Java Servlet class
- init(): the servlet container will invoke this method when the servlet is first accessed by the client. It’s common to place initialization code here. This method is called only once in the servlet’s life.
- doGet(): every time a client makes an HTTP GET request to this servlet, this method is processed. The servlet container injects two objects:
- HttpServletRequest: this object wraps all HTTP request headers so we can access GET/POST parameters as well as other HTTP headers sent from the client, via the methods getParameter() and getHeader(), respectively.
- HttpServletResponse: we use this object to deal with HTTP response such as setting HTTP response headers and sending HTML content back to the client. In this servlet’s doGet() method, we send a simple HTML code which conveys a message “Hello, I am a Java servlet!” to the client.
- doPost(): this method is invoked whenever a client makes an HTTP POST request. Similar to the doGet() method, it also takes an HttpServletRequest object and HttpServletResponse object as arguments. In this method, we retrieve values of two parameters width and height of a rectangle from the request to calculate the area and send result back to the client.
- destroy(): the servlet container will invoke this method when it needs to remove the servlet, as the containing application is being stopped or the server is shutting down.
4. Coding JSP pageCreate a JSP file called index.jsp under the directory WebContent with the following HTML code: In this JSP page:
- We put a hyperlink with the attribute href=”QuickServlet” which points to relative path of the servlet (we will configure URL mapping for the servlet shortly). Clicking on this link will generate an HTTP GET request to the server, and the servlet’s doGet() method will be invoked.
- To demonstrate sending an HTTP POST request to the servlet, we create a simple form with two text fields: width and height. The form’s attribute action is set to the servlet’s relative path. The submit button is entitled as “Calculate”.
In order to have the servlet be able to serving client’s requests, you have to declare and configure mapping for the servlet in web deployment descriptor file. Create an XML file called web.xmlunder the directory WebContentWEB-INF with the following XML code:As we can see, the servlet is declared using the <servlet> element and its children:
5. Declaring and configuring mapping for the servlet in web.xml
- <servlet-name>: specifies a descriptive name for the servlet.
- <servlet-class>: specifies fully qualified name of the servlet class.
- <servlet-name>: specifies name of a servlet which is declared using the <servlet> element.
- <url-pattern>: specifies a URL pattern to be mapped with the servlet. The pattern can be exact match, extension match or directory match. Here we specify the exact match.
Before doing the compilation, make sure you set the PATH environment variable includes the JDK_HOMEbin directory, so that the tools javac and jar can be accessed in the command line prompt.In order to compile the servlet source code, we must have a servlet API jar file available in the classpath. The servlet API jar file usually provided by the servlet container. In case of Tomcat 7.0, the jar file is placed under TOMCAT_HOMElib directory and is named as servlet-api.jar.Open a command line utility of the operating system and change the working directory to the directory QuickServlet as outlined in the directory structure. Type the following command:
6. Compiling the servlet
javac -cp TOMCAT_HOMElibservlet-api.jar' -d CLASS_DIRSRC_DIRQuickServlet.javaReplace the names TOMCAT_HOME, CLASS_DIR and SRC_DIR with the following values:
- TOMCAT_HOME: is the Tomcat’s installation directory on your computer, for example: c:Program FilesApache Software FoundationTomcat 7.0. If the path contains spaces, put it inside double quotes like this: “path contains spaces”.
- CLASS_DIR = WebContentWEB-INFclasses
- SRC_DIR = srcnetcodejavaservlet
7. Packaging the web applicationThe standard way to deploy a Java EE application is packaging it as a WAR file which can be deployed on a web server. At command prompt, type the following command (note that there is a dot at the end):
jar cfv deployQuickServletApp.war -C WebContent .The jar program will put everything in the directory WebContent into a single zip-format archive called QuickServletApp.war under the directory deploy.
Now we are ready to deploy the QuickServletApp.war file on Tomcat server. Copy it to Tomcat’s webapps directory:
8. Deploying the web application
copy deployQuickServletApp.war TOMCAT_HOMEwebappsStart Tomcat by executing the Tomcat7.exe program under TOMCAT_HOMEbin directory:From the logging in the console, we can see that the file QuickServletApp.war is deployed and the HTTP server is listening on the port number 8080.
Tomcat Vs Java Ee
9. Testing the servletNow open a web browser and type the following URL into the address bar:
http://localhost:8080/QuickServletAppBecause we don’t specify a specific page so the default page (index.jsp) is loaded as seen below:To test the servlet with an HTTP GET request, click on the hyperlink “Click here to send GET request”. The following screen is displayed:To test the servlet with an HTTP POST request, click browser’s back button and enter two numbers into the text fields width and height:Click on the Calculate button, the servlet will return the computed area as the result:So far we have gone through the journey with Java servlet from scratch. We have the project available for download in the attachment section.