Introduction To JSP and Servlet
Introduction To JSP and Servlet
Java Servlets often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.
Performance is significantly better.
Servlets execute within the address space of a Web server. It is not necessary to create a
separate process to handle each client request.
Servlets are platform-independent because they are written in Java.
Java security manager on the server enforces a set of restrictions to protect the resources
on a server machine. So Servlets are trusted.
The full functionality of the Java class libraries is available to a Servlet. It can
communicate with applets, databases, or other software via the sockets and RMI
mechanisms that you have seen already.
Servlets Architecture:
Following diagram shows the position of
Servelts in a Web Application.
Servlets Packages:
Java Servlets are Java classes run by a web server that has an interpreter that supports the Java
Servlet specification. Servlets can be created using the javax.servlet and javax.servlet.http
packages, which are a standard part of the Java's enterprise edition, an expanded version of the
Java class library that supports large-scale development projects. These classes implement the
Java Servlet and JSP specifications. Java Servlets have been created and compiled just like any
other Java class. After you install the Servlet packages and add them to your computer's
CLASSPATH, you can compile Servlets with the JDK's Java compiler or any other current
compiler.
When a user invokes a Servlet, a single instance of each Servlet gets created, with each user
request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init()
method simply creates or loads some data that will be used throughout the life of the servlet.
The init method definition looks like this:
The service () method is called by the container and service method invokes doGe, doPost,
doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method
but you override either doGet() or doPost() depending on what type of request you receive from
the client.
The doGet() and doPost() are most frequently used methods with in each service request. Here
is the signature of these two methods.
The doGet() Method
A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.
Architecture Diagram:
The following figure depicts a typical Servlet life-cycle scenario.
First the HTTP requests coming to the server are delegated to the Servlet container.
The Servlet container loads the Servlet before invoking the service() method.
Then the Servlet container handles multiple requests by spawning multiple threads, each
thread executing the service() method of a single instance of the Servlet.
Advantages of JSP
Java Server Pages often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But JSP offer several advantages in comparison with the CGI.
Performance is significantly better because JSP allows embedding Dynamic Elements in
HTML Pages itself instead of having a separate CGI files.
JSP are always compiled before it's processed by the server unlike CGI/Perl which
requires the server to load an interpreter and the target script each time the page is
requested.
Java Server Pages are built on top of the Java Servlets API, so like Servlets, JSP also has
access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.
JSP pages can be used in combination with Servlets that handle the business logic, the
model supported by Java Servlet template engines.
Finally, JSP is an integral part of Java EE, a complete platform for enterprise class applications.
This means that JSP can play a part in the simplest applications to the most complex and
demanding.
JSP - Architecture
The web server needs a JSP engine ie. container to process JSP pages. The JSP container is
responsible for intercepting requests for JSP pages. This tutorial makes use of Apache which
has built-in JSP container to support JSP pages development.
A JSP container works with the Web server to provide the runtime environment and other
services a JSP needs. It knows how to understand the special elements that are part of JSPs.
Following diagram shows the position of JSP container and JSP files in a Web Application.
JSP Processing:
The following steps explain how the web server creates the web page using JSP:
As with a normal page, your browser sends an HTTP request to the web server.
The web server recognizes that the HTTP request is for a JSP page and forwards it to a
JSP engine. This is done by using the URL or JSP page which ends with .jsp instead of
.html.
The JSP engine loads the JSP page from disk and converts it into Servlet content. This
conversion is very simple in which all template text is converted to println( ) statements
and all JSP elements are converted to Java code that implements the corresponding
dynamic behavior of the page.
The JSP engine compiles the Servlet into an executable class and forwards the original
request to a Servlet engine.
A part of the web server called the Servlet engine loads the Servlet class and executes it.
During execution, the Servlet produces an output in HTML format, which the Servlet
engine passes to the web server inside an HTTP response.
The web server forwards the HTTP response to your browser in terms of static HTML
content.
Finally web browser handles the dynamically generated HTML page inside the HTTP
response exactly as if it were a static page.
All the above mentioned steps can be shown below in the following diagram:
Typically, the JSP engine checks to see whether a Servlet for a JSP file already exists and
whether the modification date on the JSP is older than the Servlet. If the JSP is older than its
generated Servlet, the JSP container assumes that the JSP hasn't changed and that the generated
Servlet still matches the JSP's contents. This makes the process more efficient than with other
scripting languages (such as PHP) and therefore faster.
So in a way, a JSP page is really just another way to write a Servlet without having to be a Java
programming wiz. Except for the translation phase, a JSP page is handled exactly like a regular
Servlet
Configuring Apache Tomcat [Steps to create simple Servlet /JSP Web application using
Java]
Step 1: Download and install latest version of Apache Tomcat from the site.
[https://tomcat.apache.org]
Step 2: Set-up the CATALINA_HOME and CLASSPATH Environment Variable as:
JAVA_HOME = C:\Program Files\Java\jdk1.8.0_65;
PATH= C:\Program Files\Java\jdk1.8.0_65\bin;
CATALINA_HOME = C:\Program Files\Apache Software Foundation\Tomcat 9.0;
CLASSPATH= C:\Program Files\Apache Software Foundation\Tomcat 9.0\lib\servlet-
api.jar;
Step 3: Create a Tomcat Director Structure as Stated below
Step 4: Write the JSP and Servlet code to Compile and Place its Respective Folder as below.
[Note all the class files must be placed inside classes Directory under WEB-INF file]
Step 5: Write down the Mapping code for All the Servlet class under web.xml.
Step 6: Now write down the URL as [http://localhost:8080/YOUT ROOTFOLDERNAME] in
your favorite web browser. If you see output Congratulation you succeed otherwise make sure
that all the mapping correctly
@WebServlet("/HelloWorldServlet")
public class HelloWorldServlet extends HttpServlet {
public HelloWorldServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.print("<p><b><i>Welcome to Servlet
Programming!!!</i></b></p>");
out.close();
}
}
[web.xml this file is used to mapping the Servlet classes inside WEB-INF folder]
<?xml version="1.1"?>
<web-app>
<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/HelloWorldServlet</url-pattern>
</servlet-mapping>
</web-app>
Q. Create a login form in JSP file and when the user clicks on login button the username and
password should be printed by Servlet class. Write down the necessary mapping file in web.xml
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
public LoginServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.print("<h1>USERNAME:
"+request.getParameter("txtUserName")+"</h1>");
out.print("<h1>PASSWORD:
"+request.getParameter("txtPassword")+"</h1>");
out.print("<h1><a href='login.jsp'>BACK</a></h1>");
out.close();
}
Output:
Q. Create a simple JSP form to take TWO integer number and when the user clicks on ADD
button the sum of two numbers will be displayed in the Servlet Page. Write down the necessary
mapping file in web.xml
Addition.jsp [Simple JSP page as Follow]
<title>Addition</title>
</head>
<body>
<h3>Addition!</h3>
<form method="POST" action="AdditionServlet">
<table>
<tr>
<td>First Number:</td>
<td><input type="number" name="txtN1"
required="required"
placeholder="@First Number" /></td>
</tr>
<tr>
<td>Second Number:</td>
<td><input type="number" name="txtN2"
required="required" placeholder="@Second
Number" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="btnAdd" value="ADD"
/></td>
</tr>
</table>
</form>
</body>
</html>
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/AdditionServlet")
public class AdditionServlet extends HttpServlet {
public AdditionServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
double n1= Double.parseDouble(request.getParameter("txtN1"));
double n2= Double.parseDouble(request.getParameter("txtN2"));
out.print("<h3>SUM of "+ n1 +" and "+n2 + " is
"+(n1+n2)+"</h3>");
out.print("<h3><a href='addition.jsp'>BACK</a></h3>");
out.close();
}}