0% found this document useful (0 votes)
15 views

Unit 4 - Servlets and JSP

Jjjjkk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Unit 4 - Servlets and JSP

Jjjjkk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Servlets and JSP Unit 4

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.

Life Cycle of Servlet


Three methods are central to the life cycle of a servlet. These are init(), service(), and
destroy(). They are implemented by every servlet and are invoked at specific times by
the server. Let us consider a typical user scenario to understand when these methods are
called.
First, assume that a user enters a Uniform Resource Locator (URL) to a web browser.
The browser then generates an HTTP request for this URL. This request is then sent to
the appropriate server.
Second, this HTTP request is received by the web server. The server maps this request to
a particular servlet. The servlet is dynamically retrieved and loaded into the address space
of the server.
Third, the server invokes the init() method of the servlet. This method is invoked only
when the servlet is first loaded into memory. It is possible to pass initialization
parameters to the servlet so it may configure itself.
Fourth, the server invokes the service() method of the servlet. This method is called to
process the HTTP request. You will see that it is possible for the servlet to read data that
has been provided in the HTTP request. It may also formulate an HTTP response for the
client. The servlet remains in the server’s address space and is available to process any

Nawaraj Paudel Page 1


Servlets and JSP Unit 4

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.

The Servlet API


The two most commonly used packages in servlet API are javax.servlet and
javax.servlet.http. These packages represent interfaces and classes for the servlet API.
The javax.servlet package contains many interfaces and classes that are used by the
servlet or web container. These are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for http
requests only.
Interfaces and Classes in javax.servlet Package
Servlet An interface that all servlet classes must implement either directly
or indirectly. You implement it directly when you write a servlet
class that implements Servlet. You implement it indirectly when
you extend a class that implements this interface. This interface
defines three lifecycle methods and other two non-lifecycle
methods.
• public void init(ServletConfig config) throws
ServletException - The servlet container invokes this method
the first time the servlet is requested. This method is not
called at subsequent requests.
• public void service(ServletRequest request, ServletResponse
response) throws ServletException, IOException – The
servlet container invokes this method each time the servlet is
requested. You write the code that the servlet is supposed to
do here. The first time the servlet is requested, the servlet
container calls the init method and the service method. For
subsequent requests, only service is invoked.
• public void destroy() – The servlet container invokes this
method when the servlet is about to be destroyed. This
occurs when the application is unloaded or when the servlet
container is being shut down. Normally, you write clean-up
code in this method.
• public String getServletInfo() – This method returns the
description of the servlet. You can return any string that
might be useful or even null.
• public ServletConfig getServletConfig() – This method
returns the ServletConfig passed by the servlet container to
the init method. However, in order for getServletConfig to

Nawaraj Paudel Page 2


Servlets and JSP Unit 4

return a non-null value, you must have assigned the


ServletConfig passed to the init method to a class level
variable.
ServletRequest An object of ServletRequest is used to provide the client request
information to a servlet. This object is passed to the servlet’s service
method. Some of its methods of this interface are.
• public int getContentLength() – Returns the number of bytes
in the request body. If the length is not known, this method
returns -1.
• public String getContentType() – Returns the MIME type of
the request body or null if the type is not known.
• public String getParameter(String name) – Returns the value
of the specified request parameter.
• public String getProtocol() – Returns the name and version
of the protocol of this request.
ServletResponse The ServletResponse interface represents a servlet response. Prior
to invoking a servlet’s service method, the servlet container creates
a ServletResponse and pass it as the second argument to the service
method. The ServletResponse hides the complexity of sending
response to the browser. One of the methods defined in
ServletResponse is the getWriter method, which returns a
PrintWriter that can send text to the client.
There is also another method that you can use to send output to the
browser: getOutputStream. However, this method is for sending
binary data, so in most cases you will use getWriter and not
getOutputStream.
ServletConfig An object of ServletConfig is created by the web container for each
servlet. The servlet container passes a ServletConfig to the servlet’s
init method when the servlet container initializes the servlet. The
ServletConfig encapsulates configuration information that you can
pass to a servlet through @WebServlet or the deployment
descriptor. The methods of this interface are:
• public String getInitParameter(String name) – Returns the
parameter value for the specified parameter name.
• public Enumeration<String> getInitParameterNames() –
Returns an enumeration of all the initialization parameter
names.
• public String getServletName() – Returns the name of the
servlet.
• public ServletContext getServletContext() – Returns an
object of ServletContext.
ServletContext The ServletContext represents the servlet application. There is only
one context per web application. In a distributed environment where
an application is deployed simultaneously to multiple containers,

Nawaraj Paudel Page 3


Servlets and JSP Unit 4

there is one ServletContext object per Java Virtual Machine.


You can obtain the ServletContext by calling the
getServletContext method on the ServletConfig. In addition, there
is also a getServletContext method in ServletRequest that returns
the same ServletContext.
ServletContext is used to share information to all servlets in an
application from web.xml file using <context-param> element.
Some commonly used methods in ServletContext interface are:
• public String getInitParameter(String name) – Returns the
parameter value for the specified parameter name.
• public Enumeration<String> getInitParameterNames() –
Returns the names of the context's initialization parameters.
• public void setAttribute(String name,Object object) – Sets
the given object in the application scope.
• public Object getAttribute(String name) – Returns the
attribute for the specified name.
• public Enumeration<String> getInitParameterNames() –
Returns the names of the context's initialization parameters
as an Enumeration of String objects.
• public void removeAttribute(String name) – Removes the
attribute with the given name from the servlet context.
RequestDispatcher The RequestDispatcher interface provides the facility of dispatching
the request to another resource it may be html, servlet or jsp. This
interface can also be used to include the content of another resource
also. It is one of the way of servlet collaboration. There are two
methods defined in the RequestDispatcher interface.
• public void forward(ServletRequest request, ServletResponse
response)throws ServletException, IOException: Forwards a
request from a servlet to another resource (servlet, JSP file,
or HTML file) on the server.
• public void include(ServletRequest request, ServletResponse
response)throws ServletException, IOException: Includes
the content of a resource (servlet, JSP page, or HTML file)
in the response.
GenericServlet If you use Servlet interface, you have to provide implementations
for all the methods in the interface. In addition, you have to preserve
the ServletConfig object into a class level variable.
The GenericServlet abstract class comes to the rescue. The
GenericServlet implements both Servlet and ServletConfig. This
class can handle any type of request so it is protocol-independent. It
provides the implementation of all the methods of these interfaces
except the service method. The different methods in this class are:
• public void init(ServletConfig config) is used to initialize the
servlet.

Nawaraj Paudel Page 4


Servlets and JSP Unit 4

• public abstract void service(ServletRequest request,


ServletResponse response) provides service for the incoming
request. It is invoked at each time when user requests for a
servlet.
• public void destroy() is invoked only once throughout the
life cycle and indicates that servlet is being destroyed.
• public ServletConfig getServletConfig() returns the object of
ServletConfig.
• public String getServletInfo() returns information about
servlet such as writer, copyright, version etc.
• public void init() it is a convenient method for the servlet
programmers.
• public ServletContext getServletContext() returns the object
of ServletContext.
• public String getInitParameter(String name) returns the
parameter value for the given parameter name.
• public Enumeration getInitParameterNames() returns all the
parameters defined in the web.xml file.
• public String getServletName() returns the name of the
servlet object.
• public void log(String msg) writes the given message in the
servlet log file.
• public void log(String msg, Throwable t) writes the
explanatory message in the servlet log file and a stack trace.

Interfaces and Classes in javax.servlet.http Package


HttpServlet The HttpServlet class overrides the
javax.servlet.GenericServlet class. When using HttpServlet,
you will also work with the HttpServletRequest and
HttpServletResponse objects that represent the servlet request
and the servlet response, respectively. The HttpServletRequest
interface extends javax.servlet.ServletRequest and
HttpServletResponse extends javax.servlet.ServletResponse.
Some of the methods of HttpServlet are.
• public void service(ServletRequest req,ServletResponse
res) dispatches the request to the protected service method
by converting the request and response object into http
type.
• protected void service(HttpServletRequest req,
HttpServletResponse res) receives the request from the
service method, and dispatches the request to the doXXX()
method depending on the incoming http request type.
• protected void doGet(HttpServletRequest req,
HttpServletResponse res) handles the GET request. It is

Nawaraj Paudel Page 5


Servlets and JSP Unit 4

invoked by the web container.


• protected void doPost(HttpServletRequest req,
HttpServletResponse res) handles the POST request. It is
invoked by the web container.
• protected void doHead(HttpServletRequest req,
HttpServletResponse res) handles the HEAD request. It is
invoked by the web container.
• protected void doOptions(HttpServletRequest req,
HttpServletResponse res) handles the OPTIONS request. It
is invoked by the web container.
• protected void doPut(HttpServletRequest req,
HttpServletResponse res) handles the PUT request. It is
invoked by the web container.
• protected void doTrace(HttpServletRequest req,
HttpServletResponse res) handles the TRACE request. It is
invoked by the web container.
• protected void doDelete(HttpServletRequest req,
HttpServletResponse res) handles the DELETE request. It
is invoked by the web container.
• protected long getLastModified(HttpServletRequest
req) returns the time when HttpServletRequest was last
modified since midnight January 1, 1970 GMT.
HttpServletRequest HttpServletRequest represents the servlet request in the HTTP
environment. It extends the javax.servlet.ServletRequest
interface and adds several methods. Some of the methods added in
this interface are as follows.
• public String getContextPath() – Returns the portion of the
request URI that indicates the context of the request.
• public Cookie[] getCookies() – Returns an array of
Cookie objects.
• public String getHeader(String name) – Returns the value
of the specified HTTP header.
• public String getMethod() – Returns the name of the
HTTP method with which this request was made.
• public String getQueryString() – Returns the query string
in the request URL.
• public HttpSession getSession() – Returns the session
object associated with this request. If none is found,
creates a new session object.
• public HttpSession getSession(boolean create) – Returns
the current session object associated with this request. If
none is found and the create argument is true, create a
new session object.
HttpServletResponse HttpServletResponse represents the servlet response in the

Nawaraj Paudel Page 6


Servlets and JSP Unit 4

HTTP environment. Here are some of the methods defined in this


interface.
• public void addCookie(Cookie cookie) – Adds a cookie to
this response object.
• public void addHeader(String name, String value) – Adds
a header to this response object.
• public void sendRedirect(String location) – Sends a
response code that redirects the browser to the specified
location.
Cookie The Cookie class encapsulates a cookie. A cookie is stored on a
client and contains state information. Cookies are valuable for
tracking user activities. For example, assume that a user visits an
online store. A cookie can save the user’s name, address, and
other information. The user does not need to enter this data each
time he or she visits the store.
A servlet can write a cookie to a user’s machine via the
addCookie( ) method of the HttpServletResponse interface. The
data for that cookie is then included in the header of the HTTP
response that is sent to the browser. The names and values of
cookies are stored on the user’s machine.
The two constructors of Cookie class are: Cookie() and Cookie
(String name, String value). The first constructor constructs a
cookie ad second constructor constructs a cookie with a specified
name and value. Some of the useful methods of Cookie class are:
• Object clone() – returns a copy of this object.
• String getComment() – returns the comment.
• String getDomain() – returns the domain.
• int getMaxAge() – retruns the maximum age (in seconds).
• String getName() – returns the name.
• String getPath() – returns the path.
• boolean getSecure() – returns true if the cookie is secure.
Otherwise, returns false.
• String getValue() – returns the value.
• int getVersion() – returns the version.
• boolean isHttpOnly() – returns tre if the cookie has the
HttpOnly attribute.
• void setComment(String c) – sets the comment to c.
• void setDomain(String d) – sets the domain to d.
• void setHttpOnly(Boolean httpOnly) – if httpOnly is true,
then the HttpOnly attribute is added to the cookie. If
httpOnly is false, the HttpOnly attribute is removed.
• void setMaxAge(int sec) – sets the maximum age of the
cookie to secs after which cookie is deleted.
• void setPath(String p) – sets the path to p.

Nawaraj Paudel Page 7


Servlets and JSP Unit 4

• void setSecure(Boolean secure) – sets the security flag to


secure.
• void setValue(String v) – sets the value to v.
• void setVerstion(int v) – sets the version to v.

HttpSession HTTP is a stateless protocol. Each request is independent of the


previous one. However, in some applications, it is necessary to
save state information so that information can be collected from
several interactions between a browser and a server. Sessions
provide such a mechanism.
The HttpSession interface enables a servlet to read and write the
state information that is associated with an HTTP session. Several
of its methods are given below. All of these methods throw an
IllegalStateException if the session has already been invalidated.
• Object getAttribute(String attr) – returns the value
associate with the name passed in attr. Returns null if attr
is not found.
• Enumeration <String> getAttributeNames() – returns an
enumeration of the attribute names associate with the
session.
• long getCreationTime() –returns the time when this
session was created, measured in milliseconds since
midnight January 1, 1970 GMT.
• String getId() – returns a string containing the unique
identifier value.
• long getLastAccessedTime() - returns the last time the
client sent a request associated with this session, as the
number of milliseconds since midnight January 1, 1970
GMT.
• void invalidate() – invalidates this session then unbinds
any objects bound to it.
• boolean isNew() – returns true if the server created the
session and it has not yet been accessed by the client.
• void removeAttribute(String attr) – removes the attribute
specified by attr from the session.
• void setAttribute(String attr, Object val) – associates the
value passed in val with the attribute name passed in attr.
The HttpServletRequest interface provides two methods to get the
object of HttpSession. These methods are:
• HttpSession getSession() – returns the current session
associated with this request, or if the request does not have
a session, creates one.
• HttpSession getSession(boolean create) – returns the
current HttpSession associated with this request or, if there

Nawaraj Paudel Page 8


Servlets and JSP Unit 4

is no current session and create is true, returns a new


session.

Writing Servlet Application using Servlet Interface


import java.io.*;
import javax.servlet.*;
public class MyServlet implements Servlet
{
private transient ServletConfig servletConfig;
public void init(ServletConfig servletConfig) throws ServletException
{
this.servletConfig = servletConfig;
}
public ServletConfig getServletConfig()
{
return servletConfig;
}
public String getServletInfo()
{
return "My Servlet";
}
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
{
String servletName = servletConfig.getServletName();
String name = servletConfig.getInitParameter("name");
String email = servletConfig.getInitParameter("email");
ServletContext context = servletConfig.getServletContext();
String webapp = context.getInitParameter("webapp");
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<!DOCTYPE html>");
writer.println("<html>");
writer.println("<body>");
writer.println("<p>" + webapp + "</p>");
writer.println("<p>" + servletName + "</p>");
writer.println("<p>" + name + "</p>");
writer.println("<p>" + email + "</p>");
writer.println("</body>");
writer.println("</html>");
}
public void destroy()
{
}

Nawaraj Paudel Page 9


Servlets and JSP Unit 4

The Deployment Descriptor (Web.xml)


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>myservlet.MyServlet</servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>Nawaraj Paudel</param-value>
</init-param>
<init-param>
<param-name>email</param-name>
<param-value>[email protected]</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<context-param>
<param-name>webapp</param-name>
<param-value>My Web Application</param-value>
</context-param>
</web-app>

Writing Servlet Application using GenericServlet Class


import java.io.*;
import javax.servlet.*;
public class MyServlet extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
{
String servletName = getServletName();
String name = getInitParameter("name");

Nawaraj Paudel Page 10


Servlets and JSP Unit 4

String email = getInitParameter("email");


ServletContext context = getServletContext();
String webapp = context.getInitParameter("webapp");
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<!DOCTYPE html>");
writer.println("<html>");
writer.println("<body>");
writer.println("<p>" + webapp + "</p>");
writer.println("<p>" + servletName + "</p>");
writer.println("<p>" + name + "</p>");
writer.println("<p>" + email + "</p>");
writer.println("</body>");
writer.println("</html>");
}
}

Writing Servlet Application using HttpServlet Class


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
String servletName = getServletName();
String name = getInitParameter("name");
String email = getInitParameter("email");
ServletContext context = getServletContext();
String webapp = context.getInitParameter("webapp");
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<!DOCTYPE html>");
writer.println("<html>");
writer.println("<body>");
writer.println("<p>" + webapp + "</p>");
writer.println("<p>" + servletName + "</p>");
writer.println("<p>" + name + "</p>");
writer.println("<p>" + email + "</p>");
writer.println("</body>");
writer.println("</html>");
}
}

Nawaraj Paudel Page 11


Servlets and JSP Unit 4

Reading Servlet Parameters


The ServletRequest interface includes methods that allow you to read the names and
values of parameters that are included in a client request. The example below contains
two files. An HTML form defined in test.html and a servlet defined in MyServlet.java.
When Submit button of the html form is clicked, the browser will display a response that
is dynamically generated by the servlet.

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.

Nawaraj Paudel Page 12


Servlets and JSP Unit 4

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.*;

Nawaraj Paudel Page 13


Servlets and JSP Unit 4

public class GetCookieServlet extends HttpServlet


{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
Cookie[]ck = request.getCookies();
writer.println("<!DOCTYPE html>");
writer.println("<html>");
writer.println("<body>");
writer.println("<p>Welcome " + ck[0].getValue()+ "</p>");
writer.println("</body>");
writer.println("</html>");
}
}

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();

Nawaraj Paudel Page 14


Servlets and JSP Unit 4

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>");
}
}

Nawaraj Paudel Page 15


Servlets and JSP Unit 4

Java Server Pages (JSP)


JSP Introduction
There are two drawbacks associated with servlets. First, all HTML tags written in a
servlet must be enclosed in Java strings, making sending HTTP response a tedious effort.
Second, all text and HTML tags are hardcoded; as such, even minor changes to the
presentation layer, such as changing a background color, require recompilation.
JavaServer Pages (JSP) solves these two problems in servlets.
A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain
than Servlet because we can separate designing and development. It provides some
additional features such as Expression Language, JSTL (JSP Standard Tag Library),
Custom Tags etc.
Table: Comparing Servlet with JSP
Servlet JSP
Servlet is a java code. JSP is an html based code.
Writing code for servlet is harder than JSP is easy to code as it is java in html.
JSP as it is html in java.
Servlet plays a controller role in MVC JSP is the view in MVC approach for
approach. showing output.
Servlet is faster than JSP. JSP is slower than Servlet because the first
step in JSP lifecycle is the translation of
JSP to java code and then compile.
Servlet can accept all protocol requests. JSP only accept http requests.
In Servlet, we can override the service() In JSP, we cannot override its service()
method. method.
In Servlet by default session management In JSP session management is
is not enabled, user have to enable it automatically enabled.
explicitly.
In Servlet we have to implement In JSP business logic is separated from
everything like business logic and presentation logic by using javaBeans.
presentation logic in just one servlet file.
Modification in Servlet is a time JSP modification is fast, just need to click
consuming task because it includes the refresh button.
reloading, recompiling and restarting the
server.

Execution of JSP File


When the JSP page is invoked first time, the Servlet/JSP container translates the JSP file
into a JSP page implementation class, which is a Java class that implements the
javax.servlet.jsp.JspPage interface or its subinterface javax.servlet.jsp.HttpJspPage.
JspPage is a subinterface of javax.servlet.Servlet and this makes every JSP page a
servlet. HttpJspPage is obvious choice in the HTTP environment. The class name of the
generated servlet is dependent on the servlet/JSP container. You do not have to worry

Nawaraj Paudel Page 16


Servlets and JSP Unit 4

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.

Creating a Simple JSP Page


To create a JSP page, we write HTML code along with JSP code and save it by .jsp
extension. For example,
<!DOCTYPE html>
<html>
<body>
<%
out.println("<p>Hello world!</p>");
%>
</body>
</html>

JSP Implicit Objects


The servlet container passes several objects to the servlets it is running. For instance, you
get an HttpServletRequest and an HttpServletResponse in the servlet’s service method
and a ServletConfig in the init method. In addition, you can obtain an HttpSession by
calling getSession on the HttpServletRequest object.
In JSP you can retrieve those objects by using implicit objects. The table below lists the
implicit objects.
Variable of Type
request javax.servlet.http.HttpServletRequest
response javax.servlet.http.HttpServletResponse
out javax.servlet.jsp.JspWriter
session javax.servlet.http.HttpSession
pageContext javax.servlet.jsp.PageContext
application javax.servlet.http.ServletContext
config javax.servlet.http.ServletConfig
page javax.servlet.jsp.HttpJspPage
exception java.lang.Throwable
For example, the request implicit object represents the HttpServletRequest passed by the
servlet/JSP container to the servlet’s service method. You can use request as if it was a
variable reference to the HttpServletRequest. For instance, the following code retrieves
the userName parameter from the HttpServletRequest object.

Nawaraj Paudel Page 17


Servlets and JSP Unit 4

<%
String username = request.getParameter(“username”);
%>

JSP Scripting Elements


Scripting elements in JSP incorporate Java code into a JSP page. There are three types of
scripting elements: scriptlets, declarations, and expressions.
Scriplets
A scriptlet is a block of Java code. A scriptlet starts with <% and ends with %>. For
example,
<%
out.print("<p>Hello world!</p>");
%>
If a JSP page contains more than one scriplet, a scriptlet is visible to the other scriptlets
below it.
Expressions
An expression is evaluated and its result fed to the print method of the out implicit object.
An expression starts with <%= and ends with %>. For example,
<%=
"<p>Hello world!</p>"
%>

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.

Nawaraj Paudel Page 18


Servlets and JSP Unit 4

The Page Directive


You use the page directive to instruct the JSP translator on certain aspects of the current
JSP page. For example, you can tell the JSP translator the size of the buffer that should be
used for the out implicit object, what content type to use, what Java types to import, and
so on. The page directive has the following syntax:
<%@ page attribute1="value1" attribute2="value2" ... %>
The attribute1, attribute2, and so on are the page directive’s attributes. For example, we
can use import attribute as follows.
<%@page import="java.util.Date"%>
<%
out.print(new Date());
%>
Like import, there ae may other attributes for the page directive as given below.
• import: Specifies a Java type or Java types that will be imported and useable by
the Java code in this page. For example, specifying import="java.util.Date"
imports the Date class form java.util package. You can use the wildcard * to
import the whole package, such as in import="java.util.*". To import multiple
types, separate two types with a comma, such as in import="java.util.Date,
java.util.Calendar ". All types in the following packages are implicitly
imported: java.lang, javax.servlet, javax.servlet.http, javax.servlet.jsp.
• session: A value of true indicates that this page participates in session
management, and a value of false indicates otherwise. By default, the value is
true, which means the invocation of a JSP page will cause a
javax.servlet.http.HttpSession instance to be created if one does not yet exist.
• buffer: Specifies the buffer size of the out implicit object in kilobytes. The suffix
kb is mandatory. The default buffer size is 8kb or more, depending on the JSP
container. It is also possible to assign none to this attribute to indicate that no
buffering should be used, which will cause the output to be written directly to the
corresponding PrintWriter.
• autoFlush: A value of true, the default value, indicates that the buffered output
should be flushed automatically when the buffer is full. A value of false indicates
that the buffer is only flushed if the flush method of the response implicit object
is called. Consequently, an exception will be thrown in the event of buffer
overflow.
• isThreadSafe: Indicates the level of thread safety implemented in the page. JSP
authors are advised against using this attribute as it could result in a generated
servlet containing deprecated code.
• Info: Specifies the return value of the getServletInfo method of the generated
servlet.
• errorPage: Indicates the page that will handle errors that may occur in this page.
• isErrorPage: Indicates if this page is an error handler.
• contentType: Specifies the content type of the response implicit object of this
page. By default, the value is text/html.

Nawaraj Paudel Page 19


Servlets and JSP Unit 4

• 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”%>

Java Web Frameworks


Frameworks are tools with pre-written code, act as a template or skeleton, which can be
reused to create an application by simply filling with your code as needed which
enables developers to program their application with no overhead of creating each line

Nawaraj Paudel Page 20


Servlets and JSP Unit 4

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.

Nawaraj Paudel Page 21


Servlets and JSP Unit 4

• Create optimized web applications that are easy to debug.


• Compiles the Java source code into JavaScript files that can run on all major
browsers.
4. Struts: It is a very useful framework, an open-source MVC framework for creating
modern enterprise-level Java web applications that favor convention over
configuration and reduce overall development time. It comes with plugins to
support REST, AJAX, and JSON and can be easily integrated with other Java
frameworks like Spring and Hibernate.
• Super Flexible and beginner-friendly.
• Reliable, based on MVC design pattern.
• Integration with REST, JSON, and AJAX.
• Creative themes and templates make development tasks faster.
• Extend capabilities for complex development.
• Reduced development time and Effort, makes dev easier and fun.
5. Java Server Faces (JSF): It is quite similar to Struts, a free web application
developed framework, maintained by Oracle technology which simplifies building
user interfaces for Server-side applications by assembling reusable UI components
in a page. JSF is a component-based MVC framework that encapsulates various
client-side technologies and focuses more on the presentation layer to allow web
developers to create UI simply by just drag and drop.
• Rich libraries and reusable UI components.
• Easy front-end tools to use without too much coding.
• JSE helps to improve productivity and consistency.
• Enrich the user experience by adding Ajax events for validations and method
invocations.
• It provides an API to represent and manage UI components and instead of
using Java, JSF uses XML for view handling.
6. Hibernate: A stable, lightweight ORM Java framework that can easily
communicate with any database and is more convenient when working with
multiple databases. Working with Hibernate is fun using powerful APIs and several
useful tools like Mapping Editor, Wizards, and Reverse Engineering. Many big
companies including Platform, DAILY HOTEL, IBM, and Dell use Hibernate in
their tech stacks.
• Light-weight and easy to scale up, modify, and configure.
• Complex data manipulation with less coding.
• High productivity and portability.
• Used for RDBMS as well as the NoSQL database.
• Awesome Command-line tools and IDE plugins to makes your experience
pleasant.

Exercises
1. What is Servlet? Why do we need Servlet? Explain life-cycle of servlet in detail.

Nawaraj Paudel Page 22


Servlets and JSP Unit 4

2. What is Servlet API? Explain javax.servlet and javax.servlet.http packages in


detail.
3. Write a simple servlet application using Servlet interface.
4. Write a simple servlet application using GenericServlet class.
5. Write a simple servlet application using HttpServlet class.
6. How can you read servlet parameters? Explain using suitable program.
7. Explain cookie with example.
8. What is session? How can you track sessions? Explain session tracking with
suitable example.
9. What is JSP? How is it different from Servlet? How JSP file is executed?
10. Explain different implicit object in JSP.
11. Explain different scripting elements in JSP.
12. What are directives in JSP? Explain.
13. What are the benefits of using Java Web Frameworks? Explain any two
frameworks in detail.
14. Write a servlet that receives data from HTML form and inserts form data into
the database.

Nawaraj Paudel Page 23

You might also like