Unit 4 - Servlets and JSP
Unit 4 - Servlets and JSP
Unit 4
Servlets and JSP
Servlet Introduction
Java Servlet technology, or Servlet for short, is the underlying technology for developing
web applications in Java. Servlets execute on the server side of a web connection for
generating dynamic content on the web. Sun Microsystems released it in 1996 to compete
with the Common Gateway Interface (CGI).
The main problem with CGI was the fact that it suffered serious performance problems. It
was expensive in terms of processor and memory resources to create a separate process
for each client request. It was also expensive to open and close database connections for
each client request. In addition, the CGI programs were not platform independent. A
variety of different languages were used to build CGI programs. These included C, C++,
and Perl. Therefore, other techniques were introduced. Among these are servlets. Servlets
offer several advantages in comparison with CGI. First, 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. Second, servlets are platform-
independent because they are written in Java. Third, the Java security manager on the
server enforces a set of restrictions to protect the resources on a server machine. Finally,
the full functionality of the Java class libraries is available to a servlet. It can
communicate with other software via the sockets and RMI mechanisms.
A servlet application runs inside a servlet container and cannot run on its own. A servlet
container passes requests from the user to the servlet application and responses from the
servlet application back to the user.
other HTTP requests received from clients. The service() method is called for each HTTP
request.
Finally, the server may decide to unload the servlet from its memory. The algorithms by
which this determination is made are specific to each server. The server calls the
destroy() method to relinquish any resources such as file handles that are allocated for
the servlet. Important data may be saved to a persistent store. The memory allocated for
the servlet and its objects can then be garbage collected.
form.html
<!DOCTYPE html>
<html>
<body>
<form name="form1" method ="get" action="MyServlet">
Name:<input type ="text" name="name"/><br><br>
Email:<input type ="text" name="email"/><br><br>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
MyServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<!DOCTYPE html>");
writer.println("<html>");
writer.println("<body>");
writer.println("<p>Your name is " + request.getParameter("name") + "</p>");
writer.println("<p>Your email is " + request.getParameter("email") + "</p>");
writer.println("</body>");
writer.println("</html>");
}
}
Using Cookie
In the example below, when the submit button of the form is pressed, the value in the text
field is sent to AddCookieServlet via an HTTP GET request.
The AddCookieServlet gets the value of the parameter named "name". It then creates a
Cookie object that has the name "uname" and contains the value of the "name"
parameter. The cookie is then added to the header of the HTTP response via the
addCookie( ) method.
When the user clicks the hyperlink, GetCookieServlet is opened. The servlet invokes the
getCookies( ) method to read any cookies. The names and values of these cookies are
then written to the HTTP response.
form.html
<!DOCTYPE html>
<html>
<body>
<form name="form1" method ="get" action="AddCookieServlet">
<label>Name:</label><input type ="text" name="name"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
AddCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
Cookie c=new Cookie("uname",request.getParameter("name"));
response.addCookie(c);
writer.println("<!DOCTYPE html>");
writer.println("<html>");
writer.println("<body>");
writer.println("<a href='GetCookieServlet '>Click</a>");
writer.println("</body>");
writer.println("</html>");
}
}
GetCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Session Tracking
In this example, we are setting the attribute in the session scope in one servlet and getting
that value from the session scope in another servlet. To set the attribute in the session
scope, we have used the setAttribute() method of HttpSession interface and to get the
attribute, we have used the getAttribute method.
Form.html
<!DOCTYPE html>
<html>
<body>
<form name="form1" method ="get" action="FirstServlet">
<label>Name:</label><input type ="text" name="name"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
String n=request.getParameter("name");
HttpSession ses=request.getSession();
ses.setAttribute("uname",n);
writer.println("<!DOCTYPE html>");
writer.println("<html>");
writer.println("<body>");
writer.println("<p>Welcome " + n + "</p>");
writer.println("<a href='SecondServlet'>Click</a>");
writer.println("</body>");
writer.println("</html>");
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
writer.println("<!DOCTYPE html>");
writer.println("<html>");
writer.println("<body>");
writer.println("<p>Hello " + n + "</p>");
writer.println("</body>");
writer.println("</html>");
}
}
about this because you do not have to work with it directly. If there is a translation error,
an error message will be sent to the client.
If the translation was successful, the servlet/JSP container compiles the servlet class. The
container then loads and instantiates the Java bytecode as well as performs the lifecycle
operations it normally does a servlet.
For subsequent requests for the same JSP page, the servlet/JSP container checks if the
JSP page has been modified since the last time it was translated. If so, it will be re-
translated, re-compiled and executed. If not, the JSP servlet already in memory is
executed. This way, the first invocation of a JSP page always takes longer than
subsequent requests because it involves translation and compilation.
<%
String username = request.getParameter(“username”);
%>
Note that a semicolon does not appear at the end of the code inside this tag. It is
equivalent to out.print.
Declarations
You can declare variables and methods that can be used in a JSP page. You enclose a
declaration with <%! And %>. For example,
<%!
private int add(int a, int b)
{
return a + b;
}
%>
<%
out.print("Sum = " + add(6,7));
%>
Directives
Directives are the first type of JSP syntactic elements. They are instructions for the JSP
translator on how a JSP page should be translated into a servlet. There are several
directives, but only the two most important ones are page and include. The other
directives are taglib, tag, attribute, and variable.
• pageEncoding: Specifies the character encoding for this page. By default, the
value is ISO-8859-1.
• isELIgnored: Indicates whether EL expressions are ignored. EL is short for
expression language.
• Language: Specifies the scripting language used in this page. By default, its
value is java and this is the only valid value in JSP 2.2.
• Extends: Specifies the superclass that this JSP page’s implementation class must
extend. This attribute is rarely used and should only be used with extra caution.
• deferredSyntaxAllowedAsLiteral: Specifies whether or not the character
sequence #{ is allowed as a String literal in this page and translation unit. The
default value is false. #{ is important because it is a special character sequence in
the Expression Language.
• trimDirectiveWhitespaces: Indicates whether or not template text that contains
only white spaces is removed from the output. The default is false; in other words,
not to trim white spaces.
The page directive can appear anywhere in a page. The exception is when it contains the
contentType or the pageEncoding attribute, in which case it must appear before any
template data and before sending any content using Java code. This is because the content
type and the character encoding must be set prior to sending any content.
The page directive can also appear multiple times. However, an attribute that appears in
multiple page directives must have the same value. An exception to this rule is the import
attribute. The effect of the import attribute appearing in multiple page directives is
cumulative. For example, the following page directives import both java.util.ArrayList
and java.io.File.
<%@page import = “java.util.ArrayList”%>
<%@page import = “java.util.Date”%>
This is the same as
<%@page import = “java.util.ArrayList, java.util.Date”%>
As another example, here is a page directive that sets the session attribute to false and
allocates 16KB to the page buffer:
<%@page session = “false” buffer = “16kb”%>
The Include Directive
You use the include directive to include the content of another file in the current JSP
page. You can use multiple include directives in a JSP page. Modularizing a particular
content into an include file is useful if that content is used by different pages or used by a
page in different places. The syntax of the include directive is as follows:
<%@include file = “url”%>
For example,
<%@include file = “copyright.jsp”%>
of code again and again from scratch. Now if you are searching for the best tools in the
market that help you to develop a website easier, faster and better then Java is always
there for you with a large number of frameworks and most importantly most of the Java
frameworks are free and open-source. Some common frameworks are:
1. Spring: Spring is a powerful, lightweight, and most popular framework which
makes Java quicker, easier, and safer to use. This framework is very popular among
developers for its speed, simplicity, and productivity which helps to create
enterprise-level web applications with complete ease. Spring MVC and Spring Boot
made Java modern, reactive, and cloud-ready to build high-performance complex
web applications hence used by many tech-giants, including Netflix, Amazon,
Google, Microsoft, etc.
• Using Spring’s flexible and comprehensive third-party libraries you can
build any web application you can imagine.
• Start a new Spring project in seconds, with, fast startup, fast shutdown, and
optimized execution by default.
• Spring provides a lightweight container that can be triggered without a web
server or application server.
• It provides backward compatibility and easy testability of your project.
• It supports JDBC which improves productivity and reduces the error as
much as possible.
• It supports modularity and both XML and annotation-based configuration.
• Spring Boot has a huge ecosystem and community with extensive
documentation and multiple Spring tutorials
2. Grails: It is a dynamic full-stack Java framework based on the MVC design pattern.
which is easy to learn and most suitable for beginners. Grails is an object-oriented
language that enhances developer productivity. While written in Groovy it can run
on the Java platform and is perfectly compatible with Java syntax.
• Easy to Creating tags for the View.
• Built-in support for RESTful APIs.
• You can mix Groovy and Java using Grails.
• Best suitable for Rapid Development.
• Configuration features are dynamic, no need to restart the server.
3. Google Web Toolkit (GWT): It is a very popular open-source Java framework used
by a large number of developers around the world for building and optimizing
complex browser-based applications. This framework is used for the productive
development of high-performance complex web applications without being an
expert in front-end technologies like JavaScript or responsive design. It converts
Java code into JavaScript code which is a remarkable feature of GWT. Popular
Google’s applications like AdSense and AdWords are written and using this
framework.
• Google APIs are vastly used in GWT applications.
• Open-source and Developer-friendly.
• Easily create beautiful UIs without vast knowledge in front-end scripting
languages.
Exercises
1. What is Servlet? Why do we need Servlet? Explain life-cycle of servlet in detail.