Full Stack Web Development Internship Program
- 29k Enrolled Learners
- Weekend/Weekday
- Live Class
Below is the list of topics that I will be covering in this Java Servlets tutorial:
You may also go through this recording of Java Servlets Tutorial where you can understand the topics in a detailed manner with examples.
Java Servlets Tutorial | Introduction to Servlets | Edureka
This video will talk about the basics of the World Wide Web and its components. It will tell you the fundamental concepts of servlets, its life cycle and various steps to create Servlet.
Before we jump into servlets, let’s understand a few fundamentals of Web.
Web is basically a system of Internet servers that supports formatted documents. The documents are formatted using a markup language called HTML (HyperText Markup Language) that supports links to other documents, like graphics, audio, and video files.
Web consists of billions of clients and servers connected through wires and wireless networks. First, web clients make requests to a web server. Then, the web server receives the request, finds the resources and returns the response to the client. When a server answers a request, it usually sends some type of content to the client. Then, the client uses a web browser to send a request to the server. The server often sends a response back to the browser with a set of instructions written in HTML. All browsers know how to display HTML pages to the client.
Basically, this is all about the backend working of the WWW (World Wide Web). Now, let’s understand the connectivity between Web & HTTP.
A website is a collection of static files i.e. web pages such as HTML pages, images, graphics etc. A Web application is a website with dynamic functionality on the server. Google, Facebook, Twitter are examples of web applications.
So, what is the link between the Web and HTTP? Let’s now find out.
The HTTP request can be made using a variety of methods, but the ones which we use widely are Get and Post. The method name itself tells the server the kind of request that is being made, and how the rest of the message will be formatted.
Now, with the help of the below table, let’s understand the difference between Get and Post methods of HTTP.
Get | Post |
1. Data is sent in the header body | 1. Data is sent in the request body |
2. Restricted to limited data transfer | 2. Supports a large amount of data transfer |
3. It is not secured | 3. It is completely secured |
4. It can be bookmarked | 4. It cannot be bookmarked |
Now, that you have learned a few basics of web, let’s jump to the core topic and understand the concept of a servlet.
A servlet is a Java Programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. It is also a web component that is deployed on the server to create a dynamic web page.
In this figure you can see, a client sends a request to the server and the server generates the response, analyses it and sends the response to the client.
So, before we jump into the depth of Servlets, let’s see the technology that was used before servlets came into the picture.
Before servlets, we had CGI i.e. Common Gateway Interface. It is a standard way for a Web server to pass a user’s request to an application program and receives the response to forward to the user. When the user requests a Web page, the server sends back the requested page. However, when a user fills out a form on a Web page and sends it in, it is processed by an application program. The Web server typically passes the form information to a small application program. This program processes the data and sends back a confirmation message. This process of passing data back and forth between the server and the application is called the common gateway interface (CGI). It is part of the Web’s Hypertext Transfer Protocol.
But, why did we stopped using it and switched to servlets? Let’s understand this with the help of the below table:
Basis for Comparison | Common Gateway Interface | Servlets |
1. Basic | Programs are written in the native OS. | Programs employed using Java. |
2. Platform dependency | Platform dependent | Does not rely on the platform |
3. Creation of process | Each client request creates its own process. | Processes are created depending on the type of the client request. |
4. Conversion of the script | Present in the form of executables (native to the server OS). | Compiled to Java Bytecode. |
5. Runs on | Separate process | JVM |
6. Security | More vulnerable to attacks. | Can resist attacks. |
7. Speed | Slower | Faster |
8. Processing of script | Direct | Before running the scripts it is translated and compiled. |
9. Portability | Cannot be ported | Portable |
I hope that based on the above comparison, one can conclude, why Servlets are being used for Web Applications. Now, let’s move ahead with this article and understand Servlet Architecture.
Java Servlets: Servlet Architecture
The architecture, here, discusses the communication interface, protocol used, requirements of client and server, the programming with the languages and software involved. Basically, it performs the below-mentioned tasks.
Now, let’s understand the various methods in the life cycle of a servlet.
The Servlet life cycle mainly includes the following four stages,
init() and destroy() methods are called only once. Finally, a servlet is garbage collected by the garbage collector of the JVM. So this concludes the life cycle of a servlet. Now, let me guide you through the steps of creating java servlets.
Now, based on the above steps, let’s write a program and understand how a servlet works.
To run a servlet program, we should have Apache Tomcat Server installed and configured. Eclipse for Java EE provides in-built Apache Tomcat. Once the server is configured, you can start with your program. One important point to note – for any servlet program, you need 3 files – index.html file, Java class file, and web.xml file. The very first step is to create a Dynamic Web Project and then proceed further.
Now, let’s see how to add 2 numbers using servlets and display the output in the browser.
First, I will write index.html file
<!DOCTYPE HTML> <html> <body> <form action = "add"> Enter 1st number: <input type="text" name ="num1"> Enter 2nd number: <input type="text" name="num2"> </form> </body> </html>
Above program creates a form to enter the numbers for the addition operation. Without the Java class file, you can’t perform addition on 2 numbers. So let’s now create a class file.
package edureka; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Add extends HttpServlet{ public void service(HttpServletRequest req, HttpServletResponse res) throws IOException { int i = Integer.parseInt(req.getParameter("num1")); int j = Integer.parseInt(req.getParameter("num2")); int k= i+j; PrintWriter out = res.getWriter(); out.println("Result is"+k); } }
After writing the Java class file, the last step is to add mappings to the web.xml file. Let’s see how to do that.
The web.xml file will be present in the WEB-INF folder of your web content. If it is not present, then you can click on Deployment Descriptor and click on Generate Deployment Descriptor Stub. Once you get your web.xml file ready, you need to add the mappings to it. Let’s see how mapping is done using the below example:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>Basic</display-name> <servlet> <servlet-name>Addition</servlet-name> <servlet-class>edureka.Add</servlet-class> </servlet> <servlet-mapping> <servlet-name>Addition</servlet-name> <url-pattern>/add</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
Once done, you can execute the program by starting the server and get the desired output on the browser.
Let’s take another example where I will be creating a simple login servlet. Again, the very first step will be to write html file.
<!DOCTYPE html> <html> <body> <form action="Login" method="post"> <table> <tr> <td><font face="Noto Serif" size="2px">Name:</font></td> <td><input type="text" name="userName"></td> </tr> <tr> <td><font face="Noto Serif" size="2px">Password:</font></td> <td><input type="password" name="userPassword"></td> </tr> </table> <input type="submit" value="Login"> </form> </body> </html>
Next, let’s code the Java Class file.
package Edureka; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Login extends HttpServlet { protected void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { PrintWriter pw=res.getWriter(); res.setContentType("text/html"); String user=req.getParameter("userName"); String pass=req.getParameter("userPassword"); pw.println("Login Success...!"); if(user.equals("edureka") && pass.equals("edureka")) pw.println("Login Success...!"); else pw.println("Login Failed...!"); pw.close(); } }
In the above code, I have set a condition – if username and password are both equal to edureka, only then it will display successfully logged in, else login will be denied.
Let’s add the mappings to the web.xml file now.
<?xml version="1.0"encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"version="3.1"> <display-name>LoginServlet</display-name> <servlet> <servlet-name>Login</servlet-name> <servlet-class>Edureka.Login</servlet-class> </servlet> <servlet-mapping> <servlet-name>Login</servlet-name> <url-pattern>/Login</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
So, this is how a servlet is created and configured. Let’s now see what a Generic servlet is and how is it created.
A Generic servlet is a protocol-independent servlet that should always override the service() method to handle the client request. The service() method accepts two arguments, ServletRequest object, and ServletResponse object. The request object tells the servlet about the request made by the client while the response object is used to return a response back to the client. GenericServlet is an abstract class and it has only one abstract method, which is service(). That’s why when we create a Generic Servlet by extending the GenericServlet class, we must override the service() method.
Now, let’s see how to create and invoke a Generic servlet. Again I will code 3 files as shown below:
1. HTML file
We are creating an HTML file that will call the servlet once we click on the link on the web page. Create this file in the WebContent folder. The path of this file should look like this: WebContent/index.html
<html> <title>Generic Servlet Demo</title> </head> <body> <a href="welcome">Click here to call Generic Servlet</a> </body> </html>
2. Java Class file
Here we will be creating a Generic Servlet by extending GenericServlet class. When creating a GenericServlet, you must override the service() method. Right click on the src folder and create a new class file and name the file as generic. The file path should look like this: Java Resouces/src/default package/generic.java
package EdurekaGeneric; import java.io.*; importjavax.servlet.*; public class generic extends GenericServlet{ public void service(ServletRequest req,ServletResponse res) throws IOException,ServletException{ res.setContentType("text/html"); PrintWriter pwriter=res.getWriter(); pwriter.print("<html>"); pwriter.print("<body>"); pwriter.print(" <h2>Generic Servlet Example</h2> "); pwriter.print("Welcome to Edureka YouTube Channel"); pwriter.print("</body>"); pwriter.print("</html>"); } }
3. web.xml
This file can be found at this path WebContent/WEB-INF/web.xml. In this file we will map the Servlet with the specific URL. Since we are calling the welcome page upon clicking the link on index.html, it will map the welcome page to the Servlet class that we have already created above.
<?xml version="1.0"encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://xmlns.jcp.org/xml/ns/javaee"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd/"version="3.1"/> <display-name>LoginServlet</display-name> <servlet> <servlet-name>MyGenericServlet</servlet-name> <servlet-class>EdurekaGeneric.generic</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyGenericServlet</servlet-name> <url-pattern>/welcome</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
After this, start your Tomcat Server and run the servlet. You will get the desired output.
Now, let’s jump into the last section of this article, and see useful classes and interfaces of java servlets.
Servlet API consists of two important packages that encapsulate all the important classes and interfaces, namely:
With the help of below table let’s see some important classes and Interfaces of a servlet.
Servlet | Declares LifeCycle methods of the servlet |
ServletConfig | Allows the servlet to get initialization methods |
ServletContext | Enables the servlet to log access and access information |
ServletRequest | Used to read data from the client request |
ServletResponse | Used to write data to clients response |
GenericServlet | Implements Servlet and Servlet.Config Interface |
ServletInputStream | Provides input stream to read requests from the client |
ServletOutputStream | Provides output stream to write responses to the client |
ServletException | Indicates that the servlet is not available |
HttpServlet | Provides methods to handle HTTP Request & Response |
This brings us to the end of our blog on Introduction to Java Servlets. I hope you found this blog informative and added value to your knowledge.
Check out the Java Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.
Got a question for us? Please mention it in the comments section of this “Java Servlet” blog and we will get back to you as soon as possible.
Course Name | Date | Details |
---|---|---|
Java Course Online | Class Starts on 1st March,2025 1st March SAT&SUN (Weekend Batch) | View Details |
edureka.co