JSP Notes (With Programs)
JSP Notes (With Programs)
Introduction to JSP
JSP is a server side technology that does all the processing at server. It is used for
creating dynamic web applications, using java as programming language. It is an
extension of servlet because it provides more functionality than servlet by allowing users
to use expression language and JSTL(JSP Standard Tag Lib).
In JSP, you can embed Java code in HTML using JSP tags. JSP is used for creating dynamic
webpages. Dynamic webpages are usually a mix of static & dynamic content.
The static content can have text-based formats such as HTML, XML etc and the dynamic
content is generated by JSP tags using java code inside HTML .
Servlet Vs JSP
Like JSP, Servlets are also used for generating dynamic webpages. Here is the
comparison between them.
Servlets:
JSP:
Advantages of JSP
1. JSP has all the advantages of servlet, like: Better performance than
CGI Built in session features, it also inherits the the features of java
technology like – multithreading, exception handling, Database
connectivity etc.
2. JSP Enables the separation of content generation from content
presentation. Which makes it more flexible.
3. With the JSP, it is now easy for web designers to show case the
information what is needed.
4. Web Application Programmers can concentrate on how to
process/build the information.
5. It is easy to manage as business logic can be separated with
presentation logic.
There are 7 steps involved in translating a JSP page into a servlet code.
2. Compilation process- the java servlet file is compiled into a class file.
5. Initialization process-
JSP Page is initialized by _jspinit() method. It allows the page author to provide
initialization to the JSP Page. This method is called only once during the JSP life cycle.
6. Request process-
The _jspservice () method is used for request processing. This method is invoked by the
container. This method is called to handle each request. The response is produced from
within this method and then returned to the container so that it can be passed back to the
client.
7. Destroy process-
The _jspDestroy() method is used to destroy the JSP Page. Page author can call If any
cleanup is required . This method is called only once during JSP page Life Cycle.
JSP Processing
JSP Scripting elements
The scripting elements provides the ability to insert java code inside the jsp. There are
three types of scripting elements:
o scriptlet tag
o expression tag
o declaration tag
scriptlet tag
A scriptlet tag is used to execute java source code in JSP.
Syntax : <% java source code %>
Example:
<html>
<body>
<% out.print("welcome to jsp"); %>
</body> </html>
expression tag
The code placed within JSP expression tag is written to the output stream of the response.
So you need not write out.print() to write data. It is mainly used to print the values of variable
or method.
Example:
<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body> </html>
Declaration Tag
The JSP declaration tag is used to declare fields and methods. The code written inside the
jsp declaration tag is placed outside the service() method of auto generated servlet.
<html>
<head>
<title>Declaration tag Example1</title>
</head>
<body>
<%! String name="Abhineet"; %>
<%! int age=17; %>
<%= "Name is: "+ name %><br>
<%= "AGE: "+ age %>
</body> </html>
can only declare variables not methods. can declare variables as well as methods.
The declaration of scriptlet tag is placed The declaration of jsp declaration tag is placed
inside the _jspService() method. outside the _jspService() method.
exception It is an instance of
java.lang.Throwable and mainly used
for exception handling in JSP. It is only
available for error pages, which means
a JSP page should have isErrorPage
set to true in order to use exception
implicit object.
1. Cookies: Cookies are text files that allow programmers to store some information on a
client computer, and they are kept for usage tracking purposes.
2. Passing Session ID in URL: Adding and passing session ID to URL is also a way to identify
a session. However, this method is obsolete and insecure because the URL can be
tracked.
• A session object is the most commonly used implicit object implemented to store user
data to make it available on other JSP pages until the user's session is active.
• The session implicit object is an instance of a javax.servlet.http.HttpSession interface.
• This session object has different session methods to manage data within the session
scope.
Here is an example of a JSP request and session implicit objects where a user submits login
information, another JSP page receives it for processing and send redirect to output page:
1) index.html
<html> <head> <title>User login form</title>
</head> <body>
<form action="login.jsp">
Please enter Username: <input type="text" name="uname" /> <br />
<input type="submit" value="Submit Details" />
</form> </body></html>
2) login.jsp
<%@ page import = " java.util.* " %>
<%
String username = request.getParameter("uname");
if(username.equals("admin")){
session.setAttribute("uname",username);
response.sendRedirect("output.jsp");
}else{
out.print("Invalid Username");
}
%>
3) output.jsp
<html> <head>
<title>Output page: Fetching the value from session</title>
</head><body>
<%
String sessionUN = (String)session.getAttribute("uname");
out.print("Hi, and welcome ---- "+sessionUN);
%>
</body> </html>
Session is most frequently used implicit object in JSP. The main usage of it to gain access
to all the user’s data till the user session is active.
JSP Directives
The jsp directives are messages that tells the web container how to translate a JSP page
into the corresponding servlet.
A) page directive
B) include directive
C) taglib directive
A) page directive
It is used to define the properties applying the JSP page, such as the size of the allocated
buffer, imported packages and classes/interfaces, defining what type of page it is etc.
A-1) import
This tells the container what packages/classes are needed to be imported into the program.
It is similar to import keyword in java class or interface.
Syntax:
<%@page import = "value"%>
Example:
<html> <body>
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>
</body> </html>
A-2)contentType
This defines the format of data that is being exchanged between the client and the server.
It does the same thing as the setContentType method in servlet used to.
Syntax:
<%@page contentType="value"%>
Example:
<html> <body>
<%@page contentType = "text/html" %>
Today is: <%= new java.util.Date() %>
</body> </html>
A-3)language
The language attribute specifies the scripting language used in the JSP page. The default
value is "java".
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.
The isErrorPage attribute is used to declare that the current page is the error page.
Example:
//index.jsp
<html> <body>
</body> </html>
//myerrorpage.jsp
<html> <body>
</body> </html>
A-6) info: Defines the string which can be printed using the ‘getServletInfo()’ method.
Syntax:
<%@page info="value"%>
Example:
Example:
In this example, we have three jsp pages: file1.jsp, file2.jsp and index.jsp. We have
included the content of file1.jsp and file2.jsp in the index.jsp using include directive.
index.jsp
<html> <head>
<title>Main JSP Page</title> </head>
<body>
<%@ include file="file1.jsp" %>
Main JSP Page: Content between two include directives.
<%@ include file="file2.jsp" %>
</body></html>
file1.jsp
<p align="center">
This is my File1.jsp and I will include it in index.jsp using include directive
</p>
file2.jsp
<p align="center">
This is File2.jsp
</p>
Here “uri” attribute is a unique identifier in tag library descriptor and “prefix” attribute
is a tag name.
Example:
<gurutag:hello/>
</head>
<body>
</body> </html>
In this case, you must define and create a page to handle the exceptions, as in the
error.jsp page. The pages where may occur exception, define the errorPage attribute of
page directive, as in the process.jsp page.
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" %>
Standard tags begin with the jsp: prefix. There are many JSP Standard Action tag which
are used to perform some specific task.
Unlike directives, actions are re-evaluated each time the page is accessed.
The action tags are used to control the flow between pages and to use Java Bean.
jsp:forward forwards the request and response to another resource. It may be jsp,
html or another resource.
• It should be Serializable.
jsp:param sets the parameter value. It is used in forward and include mostly.
printdate.jsp
<html> <body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime());
%>
Example of </body> </html>
jsp:forward action
tag with parameter index.jsp
<html> <body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" >
<jsp:param name="name" value="JaiShriKrishna" />
</jsp:forward>
</body> </html>
printdate.jsp
<html> <body>
<% out.print("Today
is:"+java.util.Calendar.getInstance().getTime()); %>
<%= request.getParameter("name") %>
</body> </html>
In this example, we are simply forwarding the request to the
printdate.jsp file.
Example of File: index.jsp
jsp:include action <h2>this is index page</h2>
tag <jsp:include page="printdate.jsp" />
File: printdate.jsp
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime());
%>
jsp:useBean Create a Java Bean. The Java Bean is a specially constructed Java
jsp:setProperty class that provides a default, no-argument constructor, implements
jsp:getProperty the Serializable interface and it has getter and setter methods for its
properties.
• Use the useBean action to declare the JavaBean for use in the
JSP page. Once declared, the bean becomes a scripting
variable that can be accessed by both scripting elements
and other custom tags used in the JSP.
• Use the getProperty action to access get methods
and setProperty action to access set methods of the bean.
Program 1: In this example, we are simply invoking the method of the Bean class.
index.jsp file
<jsp:useBean id="obj" class=" abc.test.Calculator"/>
<%
int m=obj.cube(5);
out.print("cube of 5 is "+m);
%>
Program 2:
index.html
<form action="process.jsp" method="post">
Name:<input type="text" name="name"><br>
Password:<input type="password" name="password"><br>
Email:<input type="text" name="email"><br>
<input type="submit" value="register">
</form>
process.jsp
<jsp:useBean id="u" class="org.sssit.User"></jsp:useBean>
<jsp:setProperty property="*" name="u"/>
Record:<br>
<jsp:getProperty property="name" name="u"/><br>
<jsp:getProperty property="password" name="u"/><br>
<jsp:getProperty property="email" name="u" /><br>
User.java
package org.sssit;
Servlet plays a controller role in the ,MVC JSP is the view in the MVC approach for
approach. showing output.
Servlet can accept all protocol requests. JSP only accepts HTTP requests.
It does not have inbuilt implicit objects. In JSP there are inbuilt implicit objects.
Packages are to be imported on the top of the Packages can be imported into the JSP
program. program (i.e, bottom , middleclient-side, or top )
includes the original content in the generated servlet. calls the include method.
Applets are executed on client side. Servlets are executed on server side.
Life cycle of Applets init(), stop(), paint(), start(), Lifecycle of servlets are:- init( ), service( ),
destroy(). and destroy( ).
Packages available in Applets are :- import Packages available in servlets are:- import
java.applet.*; and import java.awt.*. javax.servlet.*; and import java.servlet.http.*;
More prone to risk as it is on client machine. Servlets are under the server security.
Utilize more network bandwidth as it executes Are executed on the servers and hence
on the client machine. require less bandwidth.
Applets are two types 1.) Untrusted Applets 2.) Servlet are two types 1.) Generic Servlet 2.)
trusted Applets HTTP Servlet