Below is the list of topics I will cover in this Servlet and JSP tutorial
-
- Servlet
- Web and HTTP
- Introduction to Servlets
- Servlet Life Cycle
- Steps to Create Servlets
- Session Tracking
- Cookies
- JSP
- Introduction to JSP
- JSP vs Servlets
- JSP Script Elements
- JSP Request and Response
- Servlet
You can also go through this Servlet and JSP Tutorial recording where you can understand the topics in detail with examples.
Servlet and JSP Tutorial: Web and HTTP
Web is an Internet server system that supports formatted documents. Documents are formatted using a markup language called HTML (HyperText Markup Language) which supports links to other documents such as graphics, audio and video files, etc.
-
Loading a Servlet
When a server starts, the servlet container is deployed and loads all servlets.
-
Initialize the servlet
Next, a servlet is initialized by calling the init() method. The Servlet container calls the Servlet.init() method to notify that this Servlet instance has been successfully created and is about to be put into service.
-
Managing requests
The service() method is then called by the servlet to process a client request and is invoked to inform the servlet of the client’s requests.
-
Servlet destruction
Finally, a servlet is terminated by calling destroy(). The destroy() method is executed only once during the lifetime of a Servlet and signals the end of the Servlet instance.
The init() and destroy() methods are called only once. Finally, a servlet is garbage collected by the JVM’s garbage collector. So this concludes the life cycle of a servlet. Now let me walk you through the steps of creating Java servlets.
Servlet and JSP Tutorial: Steps of Creating a Servlet
To create a servlet , we need to follow a few steps in order. They are as follows:
- Create a directory structure
- Create a servlet
- Compile the servlet
- Add mappings to the web .xml
- Start the server and deploy the project
- Access the servlet
Now, based on the steps above, let’s create a program to better understand how a servlet works.
To run a servlet program, we must have Apache Tomcat Server installed and configured. Eclipse for Java EE provides built-in Apache Tomcat. Once the server is set up, you can start 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 first step is to create a dynamic web project and then continue.
Now let’s take an example where I will create a simple login servlet and display the result in the browser.
First, I’ll create the file index.html
Name : | |
Password: |
Next, let’s go encode Java Class file.
Edureka package; 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 successful…!”) if(user.equals(“edureka”) && pass.equals(“edureka”)) pw.println(“Login successful…!”) ; else pw.println(“Login failed…!”); pw.close(); } }
In the above code, I set a condition: if the username and password are equal to edureka, only then it will show successfully logged in, otherwise login will be denied session. After writing the Java class file, the last step is to add mappings to the web.xml file. Let’s see how to do it.
The web.xml file will be present in the WEB-INF folder of your web content. If it is not present, you can click Deployment Descriptor and click Generate Deployment Descriptor Stub.Once you have your web.xml file ready, you need to add the mappings to it. Let’s see how the mapping is done using the following example:
<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”> LoginServlet Login Edureka.Login Login /Login index.html
This is how to create and configure a servlet. Now let’s see what a generic servlet is and how it is created.
Generic Servlets
It is a protocol-independent servlet that must override the service( ) method to handle customer request. The service() method accepts two arguments, the ServletRequest object and the ServletResponse object. The job of the request object is to inform the servlet about the request made by the client, while the response object returns a response to the client. GenericServlet is an abstract class and has only one abstract method, which is service(). That’s the whole concept when we create a generic servlet by extending the GenericServlet class, we need to override the service() method.
Now, let’s see how to create and invoke a generic servlet. Again I will code 3 files as below:
HTML file
We are creating an HTML file that will call the servlet once we click the link in the Web page. Create this file in the WebContent folder. The path to this file should look like this: WebContent/index.html
Java class file
Here we will create a generic servlet by extending the 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 generic. The file path should look like this: Java Resources/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(“”); pwriter.print(“”); pwriter.print(”
Generic Servlet Example
“); pwriter.print(“Welcome to Edureka’s YouTube channel”); pwriter.print(“”); pwriter.print(“”); } }
web.xmlThis file can be found at this path WebContent/WEB-INF/web.xml. In this file, we will map the Servlet to the specific URL. Since we are calling the welcome page when the link is clicked in index.html, it will assign the welcome page to the Servlet class we already created earlier.
MyGenericServlet EdurekaGeneric.generic MyGenericServlet /welcome
After this, start your Tomcat server and run the servlet. You will get the desired output. So this was all about Generic Servlets. Now let’s go further and understand the concept of session tracking.
Servlet and JSP Tutorial: Session Tracking
Session it simply means a particular time interval. Session tracking is a technique for maintaining state (data) of a user, also known as session management in servlet. So, each time the user requests the server, the server treats the request as a new request.
The following figure shows how each request from the client is treated as a new request.
To recognize particular user, we need session tracking. Now let’s go further and see one of the session tracking techniques, i.e. cookies.
Servlet and JSP Tutorial: Cookies
A cookie is a small piece of information that persists across multiple request requests. the clients . A cookie has a name, a unique value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.
How does the cookie work?
As it is a session tracking technique, by default each request is considered as a new request.
In this, we add a cookie with the response from the servlet. So, the cookie is stored in the browser’s cache. After that, if the user sends a request, a cookie is added with the request by default.
Now that you understand how cookies work, let’s look at a small example illustrating the use of cookies.
Let’s see an example of creating a cookie, adding the response, and retrieving the results. Here I will write 2 Java class files, ie MyServlet1 and MyServlet2.
File: MyServlet1
Edureka package; import java.io.*; import javax.servlet.*; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; @WebServlet(“/login”) public class MyServlet1 extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) { try{ response.setContentType(“text/html”); PrintWriter pwriter = response.getWriter(); String name = request.getParameter(“userName”); String password = request.getParameter(“userPassword”); pwriter.print(“Hello here:”+name); pwriter.print(“Your password is: “+password); //Creating two cookies Cookie c1=new Cookie(“userName”,name); Cookie c2=new Cookie(“usernamePassword”,password); //Add the cookies to the response header response.addCookie(c1); response.addCookie(c2); pwriter.print(” View details“); pwriter. close(); }catch(Exception exp){ System.out.println(exp); } } }
File: MyServlet2
Edureka package; import java.io.*; import javax.servlet.*; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; @WebServlet(“/welcomehere”) public class MyServlet2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType(“text/html”); PrintWriter pwriter = response.getWriter(); //Reading cookies Cookie[] c=request.getCookies(); //Displaying the username value of the cookie pwriter.print(“Name here: “+c[0].getValue()); pwriter.print(“Password: “+c[1].getValue()); //pwriter.print(” View details“); pwriter. close(); }catch(Exception exp){ System.out.println(exp); } } }
Now, let’s create a simple HTML form for cookies.
Username: Password:
Now the last step is to create an XML file and add all the mappings to it.
Servlet1 Edureka.MyServlet1 Servlet1 /login Servlet2 Edureka.MyServlet2 Servlet2 /welcomehere
You are now all set to run. You can run the code and get the desired result. This is how a cookie works. So that was all about Servlets. If you want to learn advanced Java in depth, you can refer to this Advanced Java Tutorial. Now that you have some knowledge about servlets, let’s move on and understand what Java server pages are.
Servlets and JSP Tutorial: Java Server Pages
JSP or Java Server Pages is a technology used to create web applications just like Servlet technology. It is an extension of Servlet as it provides more features than a servlet like expression language, JSTL etc. A JSP page consists of HTML tags and JSP tags. JSP pages are easier to maintain than Servlet because we can separate design and development.
Now since we know what JSP is, let’s compare JSP vs Servlets and understand which one is best suited for the web.
Servlet and JSP Tutorial: Advantages of JSP over Servlets
JSPServletsServlet extensionNot a servlet extensionEasy to maintainA bit complicatedNo need to recompile or redeployThe code must be recompiledLess code than a servletMore code compared to JSP
I hope you understood the difference between JSP and Servlets. Now, let’s go further and understand script elements.
Servlet and JSP Tutorial: JSP Script Elements
Script Elements scripts provide the ability to embed Java code within the JSP. There are three types of script elements:
- scriptlet tag – A scriptlet tag is used to execute Java source code in JSP. Syntax:
In this example, we have created two files index.html and welcome.jsp. The index.html file gets the username of the user and the welcome.jsp file prints the username with the welcome message. Now let’s look at the code.
File: index.html
File: welcome.jsp
- expression tag : Code placed inside the JSP expression tag is written to the output stream of the answer. So you don’t need to write out.print() to write data. It is mainly used to print the values of the variable or method. Syntax:
Now let’s take a small example of displaying the current time. To display the current time, we have used the getTime() method of the Calendar class. getTime() is an instance method of the Calendar class, so we called it after getting the instance of the Calendar class using the getInstance() method.
File: index.jsp
Current time:
- declaration tag – The JSP declaration tag is used to declare fields and methods. Code written inside the JSP declaration tag is placed outside of the service() method of an automatically generated servlet. So it doesn’t get memory on every request. Syntax:
In the following JSP declaration tag example, we are defining the method that returns the cube of a given number and calling this method from the expression tag JSP. But we can also use the JSP scriptlet tag to call the declared method. Let’s see how. File: index.jsp
So this is all about JSP Scripting Elements. Now let’s move on and look at JSP request and response objects.
Servlet and JSP Tutorial: JSP Request and Response Objects
JSP Request is an implicit object of type HttpServletRequest that the web container creates for each JSP request. It can be used to get information from the request, such as a parameter, header information, remote address, server name, server port, content-type, character encoding, etc. It can also be used to set, get, and remove attributes from the JSP request scope.
Let’s look at the simple implicit object request example where we are printing the username with a welcome message. Let’s see how.
JSP Implicit Request Object Example
File: index.html
File: welcome.jsp
JSP implicit response object
In JSP, the response is an implicit object of type HttpServletResponse. The web container instantiates the HttpServletResponse for each JSP request. It can be used to add or manipulate responses, such as redirecting the response to another resource, sending an error, etc.
Let’s look at the implicit response object example where we are redirecting the response to Google.
Example Implicit Response Object
File: index.html
File: welcome.jsp
So, this is how request and response objects work. This leads to the end of the Servlet and JSP tutorial article. I hope this blog has been informative and added value to your knowledge.
Check out Java certification training from Edureka, a trusted online learning company with a network of over 250,000 satisfied students spread all over the world. Edureka’s Java J2EE and SOA Training and Certification course is designed for students and professionals who want to be Java developers. The course is designed to give you a head start on Java programming and train you in basic and advanced Java concepts along with various Java frameworks such as Hibernate and Spring.
If you want to start a career in Node JS Field then check out the Node JS Training Course from Edureka, a trusted e-learning company with a network of over 250,000 satisfied students spread across the globe.
I have a question for us? Mention it in the comment section of this “Java Servlet” blog and we will get back to you as soon as possible.
.