Unit-11 Web Development Using JSP (E-next.in)
Unit-11 Web Development Using JSP (E-next.in)
Q.1 What is JSP? Explain JSP Life Cycle with suitable example.
Java Server Pages (JSP):
Java Server Pages (JSP) is a technology that helps software developers create
dynamically generated web pages based on HTML, XML, or other document types.
It is a technology which helps developers insert java code in HTML pages by making
use of special JSP tags, most of which start with.
It can be thought of as an extension to servlet because it provides more functionality
than servlet such as expression language, jstl etc.
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, Custom Tag etc.
JSP tags can be used for a variety of purposes, such as retrieving information from a
database or registering user preferences, accessing JavaBeans components, passing
control between pages and sharing information between requests, pages etc.
To deploy and run Java Server Pages, a compatible web server with a servlet
container, such as Apache Tomcat or Jetty, is required.
SP pages are saved with .jsp extension which lets the server know that this is a JSP
page and needs to go through JSP life cycle stages.
When client makes a request to Server, it first goes to container. Then container
checks whether the servlet class is older than jsp page( To ensure that the JSP file got
modified).
If this is the case then container does the translation again (converts JSP to Servlet)
otherwise it skips the translation phase (i.e. if JSP webpage is not modified then it
doesn’t do the translation to improve the performance as this phase takes time and
to repeat this step every time is not time feasible)
2) Compilation:
Servlet page is compiled by the compiler and gets converted into the class file.
3) Loading:
Loads the corresponding servlet class.
4) Instantiation:
Instantiates the servlet class.
5) Initialization:
When a container loads a JSP it invokes the jspInit() method before servicing any
requests.
If you need to perform JSP-specific initialization, override the jspInit() Typically
initialization is performed only once and as with the servlet init method, you
generally initialize database connections, open files, and create lookup tables in the
jspInit method.
6) RequestProcessing:
This phase of the JSP life cycle represents all interactions with requests until the JSP
is destroyed.
A new thread is then gets created, which invokes the_jspService() method.
Whenever a browser requests a JSP and the page has been loaded and initialized,
the JSP engine invokes the _jspService() method in the JSP.
The _jspService() method of a JSP is invoked once per a request and is responsible for
generating the response for that request and this method is also responsible for generating
responses to all seven of the HTTP methods ie. GET, POST, DELETE etc.
7) Destruction:
Invokes the jspDestroy() method to destroy the instance of the servlet class.
Advantages of JSP:
1. HTML friendly simple and easy language and tags.
2. Supports Java Code.
3. Supports standard Web site development tools.
4. The JSP serves all facilities of Java i.e. write once run anywhere.
5. JSP is ideal for Web based Technology.
6. The JSP pages are translated and compiled into JAVA Servlet but are easier to
develop than JAVA Servlet.
7. JSP containers provide easy coding for accessing standard objects and actions.
8. JSP acquire all the benefits provided by JAVA Servlets and web container
environment.
9. The JSP use HTTP as default request /response communication model.
Disadvantages of JSP:
1. As JSP pages are translated to servlets and compiled, it is difficult to trace errors
occurred in JSP pages.
2. JSP pages require double the disk space to hold the JSP page.
3. JSP pages require more time when accessed for the first time as they are to be
compiled on the server.
4. Difficult looping in JSP.
HTML Code:
<form method=post action=”display.jsp”>
<pre>
</pre>
</form>
JSP Code:
<%
String a,b,c,d;
A=request.getParameter(“t1”);
B= request.getParameter(“t2”);
C= request.getParameter(“t3”);
D= request.getParameter(“r1”);
JSP Processing:
The following steps explain how the web server creates the Webpage using JSP:
1) As with a normal page, your browser sends an HTTP request to the web server.
2) 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.
3) The JSP engine loads the JSP page from disk and converts it into a 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. This code implements
the corresponding dynamic behavior of the page.
4) The JSP engine compiles the servlet into an executable class and forwards the
original request to a servlet engine.
5) 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. The
output is furthur passed on to the web server by the servlet engine inside an HTTP
response.
6) The web server forwards the HTTP response to your browser in terms of static HTML
content.
7) Finally, the 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 seen 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 the 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.
Request HttpServletRequest
Response HttpServletResponse
Out JspWriter
Session HttpSession
application ServletContext
Config ServletConfig
pageContext PageContext
page Object
exception Throwable
2) response
Setting headers, cookies for the client and sending response to the client.
Response object has page scope.
It encapsulates the response generated by JSP.
Instance of HttpServletResponse
3) out
This is the PrintWriter object used to send output to the client.
The initial JspWriter object is instantiated differently depending on whether the page
is buffered or not.
The JspWriter object contains most of the same methods as the java.io.PrintWriter
class
Instance of a javax.servlet.jsp.JspWriter
4) session
HTTP is a stateless protocol
In web applications, a client’s interaction with the application will span many
requests and responses.
To join all of them into one conversation between client and server, sessions are
used.
Sessions are used to maintain the state and user identity across multiple page
requests.
The session object has session scope.
Provides access to session data and information about the session.
Instance of HTTP Session.
5) application
Represents the application to which JSP belongs.
The object holds references to other objects that more than one user may require
access to i.e database connection pool shared by all users.
Application object has application scope.
Instance of ServletContext.
6) config
Contains initialisation parameters, defined in deployment descriptor and the
ServletContext object.
The config object has page scope.
Used to pass information to a servlet or JSP page during initialization.
Instance of ServletConfig.
7) page context
Implements methods for transferring control from the current page to another page
either temporarily or permanently.
PageContext object has page scope.
Provides methods for accessing all other objects and attributes for holding data that
is shared between multiple components in the same page. Rarely used
Instance of javax.servlet.jsp.PageContext.
8) page
Page object represents the JSP page itself.
Synonym for this.
Page object has page scope.
Rarely used.
Instance of java.lang.Object.
9) exception
Refers to runtime Exception that results in an error page being invoked.
The exception object is available only in an error page.
Exception object has a page scope.
Instance of java.lang.Throwable.
Q.4 What are actions in JSP? Explain any four actions in JSP with a program.
Action elements:
There are many JSP action tags or elements. Each JSP action tag is used to perform
some specific tasks.
The action tags are used to control the flow between pages and to use Java Bean.
The jsp:useBean, jsp:setProperty and jsp:getProperty tags are used for bean development.
So we will see these tags in bean developement.
index.jsp
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" />
</body>
</html>
printdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
index.jsp
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" >
<jsp:param name="name" value="ABC" />
</jsp:forward>
</body>
</html>
printdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
<%= request.getParameter("name") %>
</body>
</html>
File: index.jsp
<h2>this is index page</h2>
<jsp:include page="printdate.jsp" />
<h2>end section of index page</h2>
File: printdate.jsp
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
package mypack;
public class Employee implements java.io.Serializable
{
private int id;
private String name;
public Employee(){}
package mypack;
public class Test
{
public static void main(String args[])
{
Employee e=new Employee(); //object is created
e.setName("Subodh"); //setting value to the object
System.out.println(e.getName());
}
}
Note: There are two ways to provide values to the object, one way is by constructor and
second is by setter method.
1. page: specifies that you can use this bean within the JSP page. The
default scope is page.
2. request: specifies that you can use this bean from any JSP page that
processes the same request. It has wider scope than page.
3. session: specifies that you can use this bean from any JSP page in the
same session whether processes the same request or not. It has wider
scope than request.
4. application: specifies that you can use this bean from any JSP page in
the same application. It has wider scope than session.
class: instantiates the specified bean class (i.e. creates an object of the bean class)
but it must have no-arg or no constructor and must not be abstract.
type: provides the bean a data type if the bean already exists in the scope. It is
mainly used with class or beanName attribute. If you use it without class or beanName,
no bean is instantiated.
beanName: instantiates the bean using the java.beans.Beans.instantiate() method.
index.jsp file
<jsp:useBean id="obj" class="ABC"/>
<%
int m=obj.cube(5);
out.print("cube of 5 is "+m);
%>
Output:
Example of jsp:setProperty action tag if you have to set all the values of incoming request
in the bean:
<jsp:setProperty name="bean" property="*" />
Example of jsp:setProperty action tag if you have to set value of the incoming specific
property:
<jsp:setProperty name="bean" property="username" />
Example of jsp:setProperty action tag if you have to set a specific value in the property:
<jsp:setProperty name="bean" property="username" value="ABC" />
1) import:
The import attribute is used to import class,interface or all the members of a
package.
It is similar to import keyword in java class or interface.
2) contentType:
The contentType attribute defines the MIME (Multipurpose Internet Mail Extension)
type of the HTTP response.
The default value is "text/html; charset=ISO-8859-1".
3) extends:
The extends attribute defines the parent class that will be inherited by the generated
servlet. It is rarely used.
4) info:
This attribute simply sets the information of the JSP page which is retrieved later by
using getServletInfo() method of Servlet interface.
The web container will create a method getServletInfo() in the resulting servlet.
For example:
public String getServletInfo()
{
return "composed by ABC";
}
5) buffer:
The buffer attribute sets the buffer size in kilobytes to handle output generated by
the JSP page. The default size of the buffer is 8Kb.
6) language:
The language attribute specifies the scripting language used in the JSP page. The
default value is "java".
7) isELIgnored:
We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By
default its value is false i.e. Expression Language is enabled by default. We see
Expression Language later.
<%@ page isELIgnored="true" %> //Now EL will be ignored
8) isThreadSafe:
Servlet and JSP both are multithreaded. If you want to control this behaviour of JSP
page, you can use isThreadSafe attribute of page directive.
The value of isThreadSafe value is true. If you make it false, the web container will
serialize the multiple requests, i.e. it will wait until the JSP finishes responding to a
request before passing another request to it.
The web container in such a case, will generate the servlet as:
public class SimplePage_jsp extends HttpJspBase
implements SingleThreadModel
{
.......
}
9) errorPage:
The errorPage attribute is used to define the error page, if exception occurs in the
current page, it will be redirected to the error page.
10) isErrorPage:
The isErrorPage attribute is used to declare that the current page is the error page.
Note: The exception object can only be used in the error page.
<html> <body>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body> </html>
Note: The include directive includes the original content, so the actual page size grows at
runtime.
<html>
<body>
<%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
<mytag:currentDate/>
</body>
</html>
File: MyTagHandler.java
package com.javatpoint.sonoo;
import java.util.Calendar;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
File: mytags.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>http://tomcat.apache.org/example-taglib</uri>
<tag>
<name>today</name>
<tag-class>com.javatpoint.sonoo.MyTagHandler</tag-class>
</tag>
</taglib>
File: index.jsp:
<%@ taglib uri="WEB-INF/mytags.tld" prefix="m" %>
Current Date and Time is: <m:today/>
Output:
There are mainly three groups of jsp tags(elements) available in java server page:
1. JSP scripting elements:
a) JSP scriptlet tag
b) JSP expression tag
c) JSP declaration tag
d) Comment tag
2. JSP directive elements:
a) page directive
b) include directive
c) taglib directive
3. JSP standard action elements:
1) scriptlet tag:
A scriptlet is a valid code in java and is placed in the jspService() method of the JSP
engine at the time of running.
There are variables available exclusively for the scriplets. They are request, response,
out,session and pageContext, application, config and exception.
index.html:
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
welcome.jsp:
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</form>
</body>
</html>
Note: Do not end your statement with semicolon in case of expression tag.
index.jsp
<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
index.html:
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>
welcome.jsp:
<html>
<body>
<%= "Welcome "+request.getParameter("uname") %>
</form>
</body>
</html>
Difference between the jsp scriptlet tag and jsp declaration tag ?
Jsp Scriptlet Tag Jsp Declaration Tag
The jsp scriptlet tag can only declare The jsp declaration tag can declare variables
variables not methods. as well as methods.
The declaration of scriptlet tag is placed The declaration of jsp declaration tag is
inside the _jspService() method. placed outside the _jspService() method.
index.jsp
<html>
<body>
<%!
int cube(int n)
{
return n*n*n*;
}
%>
4) JSP Comment:
There is only one type of JSP comment available by JSP specification.
This JSP comment tag tells the JSP container to ignore the comment part from
compilation. That is, the commented part of source code is not considered for the
content parsed for ‘response’.
Example:
<%-- This JSP comment part will not be included in the response object --%>
There are a small number of special constructs you can use in various cases to insert
comments or characters that would otherwise be treated specially.
Here's a summary:
Syntax Purpose
<%-- comment --%> A JSP comment. Ignored by the JSP engine.
<!-- comment --> An HTML comment. Ignored by the browser.
<\% Represents static <% literal.
%\> Represents static %> literal.
\' A single quote in an attribute that uses single quotes.
\" A double quote in an attribute that uses double quotes.
errorPage attribute in a page directive informs the Web Container that if an exception
occurs in the current page, forward the request to the specified error page.
sum.jsp
Whenever an exception occurs in sum.jsp page the user is redirected to the error.jsp page,
where either you can display a nice message, or you can also print the exception trace into a
file/database in the background, to check later what caused the error.
index.jsp:
<form action="process.jsp">
No1:<input type="text" name="n1" /><br/><br/>
No1:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="divide"/>
</form>
process.jsp:
<%@ page errorPage="error.jsp" %>
<%
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);
%>
error.jsp:
<%@ page isErrorPage="true" %>
<h3>Sorry an exception occured!</h3>
Exception is: <%= exception %>
2. JSTL Formatting: JSTL Formatting library provides tags to format text, date, number for
Internationalised web sites. Url to include JSTL Formatting Tags inside JSP page is →
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
3. JSTL sql: JSTL SQL library provides support for Relational Database Connection and tags
to perform operations like insert, delete, update, select etc on SQL databases. Url to
include JSTL SQL Tag inside JSP page is →
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
4. JSTL XML: JSTL XML library provides support for XML processing. It provides flow
control, transformation features etc. Url to include JSTL XML Tag inside JSP page is →
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
5. JSTL functions: JSTL functions library provides support for string manipulation. Url to
include JSTL Function Tag inside JSP page is →
<%@ taglib prefix="fn" uri= "http://java.sun.com/jsp/jstl/functions" %>