Java Server Pages(JSP) is a server-side programming
technology that enables the creation of dynamic,
platform-independent method for building Web-based
applications. JSP have access to the entire family of Java
APIs, including the JDBC API to access enterprise
databases.
3.
• JavaServer Pages(JSP) is a technology for developing Webpages that
supports dynamic content. This helps developers insert java code in HTML
pages by making use of special JSP tags, most of which start with <% and end
with %>.
• A JavaServer Pages component is a type of Java servlet that is designed to
fulfill the role of a user interface for a Java web application. Web developers
write JSPs as text files that combine HTML or XHTML code, XML elements,
and embedded JSP actions and commands.
• Using JSP, you can collect input from users through Webpage forms, present
records from a database or another source, and create Webpages
dynamically.
• 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.
4.
• A JSPis simpler to create that a java servlet because a JSP is
written in HTML rather than with java programming
language. This means that the JSP isn’t cluttered with many
println() methods as found in java servlet. However, a JSP
offers basically the same features found in a java servlet
because a JSP is converted to java servlet the first time that a
client requests the JSP.
5.
JSP Architecture
• JSPsare built on top of sun's servlet technology. Jsps r sciential an
HTML page with special jsp tags embedded. These jsp tags can
contain Java code.
• The jsp file extension is dot jsp rather than .htm or .html jsp engine
parses the .jsp and creates a Java servlet source file.
• It then compiles the source file into a class file this is done the first
time and this is why the jsp is probably slower the first time it is
accessed.
• Any time after this the special compile servlet is executed and is
there for returns faster.
7.
JSP Life Cycle
•Compilation
• Initialization
• Execution
• Cleanup
8.
JSP Compilation
• Whena browser asks for a JSP, the JSP engine first
checks to see whether it needs to compile the page. If
the page has never been compiled, or if the JSP has
been modified since it was last compiled, the JSP engine
compiles the page.
• Parsing the JSP.
• Turning the JSP into a servlet.
• Compiling the servlet.
9.
JSP Initialization
• Whena container loads a JSP it invokes the jspInit() method before
servicing any requests. If you need to perform JSP-specific initialization,
override the jspInit() method −
public void jspInit(){
// Initialization code...
}
• 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.
10.
JSP Execution
• Thisphase of the JSP life cycle represents all interactions with requests until
the JSP is destroyed.
• 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 takes an HttpServletRequest and an
HttpServletResponse as its parameters as follows −
void _jspService(HttpServletRequest request,
HttpServletResponse response) {
// Service handling code...}
• The _jspService() method of a JSP is invoked on request basis. This 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,
i.e, GET, POST, DELETE, etc.
11.
JSP Cleanup
• Thedestruction phase of the JSP life cycle represents when a JSP is
being removed from use by a container.
• The jspDestroy() method is the JSP equivalent of the destroy method
for servlets. Override jspDestroy when you need to perform any
cleanup, such as releasing database connections or closing open files.
• The jspDestroy() method has the following form −
public void jspDestroy() {
// Your cleanup code goes here.
}
12.
JSP Tags
• JSPprogram contains a combination of HTML tags and JSP tags. JSP
tags define java code that is to be executed before the output of the
JSP program is sent to the browser.
• JSP tag begins with a <% which is followed by javacode and ends with
%>.
• There is also XML version of JSP tags which are formatted as
<jsp:TagID></JSP:TagID>
• JSP tags are embedded into HTML component of a JSP program and
are processed by a JSP virtual engine such as Tomcat.
• Server reads the JSP program when called by browser and resolves JSP
tags then sends HTML related tags and information to the browser.
13.
Types of JSPtags: or Elements of JSP
• Comment tag: JSP comment marks text or statements that the JSP
container should ignore. A JSP comment is useful when you want to hide or
"comment out", a part of your JSP page.
• Syntax: <%-- This is JSP comment --%>
<html>
<head>
<title>A Comment Test</title>
</head>
<body> <h2>A Test of Comments</h2>
<%-- This comment will not be visible in the page source --%>
</body>
</html>
14.
•JSP Declaration tag:Adeclaration declares one or more variables or
methods that you can use in Java code later in the JSP file. You must declare
the variable or method before you use it in the JSP file.
Syntax: <%! declaration; [ declaration; ]+ ... %>
You can write XML equivalent of the above syntax as follows:
<jsp:declaration>
code fragment
</jsp:declaration>
• Example
<%! int i = 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>
15.
•Directive tags: AJSP directive affects the overall structure of the servlet class.
It usually has the following form:
<%@ directive attribute="value" %>
• There are three types of directive tag:
• These tags commands the JSP virtual engine to perform a specific task, such as
importing a java package required by objects and methods used in a declaration
statement.
Directive Description
<%@ page ... %> Defines page-dependent attributes, such as scripting language,
error page, and buffering requirements.
<%@ include ... %> Includes a file during the translation phase.
<%@ taglib ... %> Declares a tag library, containing custom actions, used in the page
Expression tags
• AJSP expression element contains a scripting language expression
that is evaluated, converted to a String, and inserted where the
expression appears in the JSP file.
• Because the value of an expression is converted to a String, you
can use an expression within a line of text, whether or not it is
tagged with HTML, in a JSP file.
• The expression element can contain any expression that is valid
according to the Java Language specification, but you cannot use a
semicolon to end an expression.
18.
• syntax ofJSP Expression:
<%= expression %>
• You can write XML equivalent of the above syntax as follows:
<jsp:expression>
expression
</jsp:expression>
Example for JSP Expression:
<html>
<head><title>A Comment Test</title></head>
<body>
<p> Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p> </body>
</html>
19.
Scriplet Tags:
• Ascriptlet can contain any number of JAVA language statements,
variable or method declarations, or expressions that are valid in the
page scripting language.
syntax of Scriptlet:
<% code fragment %>
• You can write XML equivalent of the above syntax as follows:
<jsp:scriptlet>
code fragment
</jsp:scriptlet>
20.
• Any text,HTML tags, or JSP elements you write must be outside the
scriptlet.
• Following is the simple and first example for JSP:
<html>
<head>
<title>Hello World</title>
</head>
<body> Hello World!<br/> <% out.println("Your IP
address is " + request.getRemoteAddr()); %>
</body>
</html>
21.
Variables and Objects:
Wecan declare java variables and objects that are used in JSP program using
same coding technique as used to declare them in Java.
<html
<head>
<title> JSP Programming</title>
</head>
<body>
<%! int age=29;%>
<p> your age is: <%=age%></p>
</body>
</html>
22.
Declaring multiple variablewithin a single JSP tag:
<html>
<head>
<title>JSP Programming</title>
</head>
<body>
<%! int age=29;
float salary;
int empnumber;
%>
</body>
<html>
23.
Declaring objects andarrays within a single JSP tag
<html>
<head>
<title>JSP Programming<//title>
</head>
<body>
<%! String Name;
String [ ] Telephone={“+919980556548”, “+918887548965”};
String Company=new String();
Vector Assignments=new Vector();
int[ ] Grade = { 100, 82, 93};
%>
</body>
</html>
24.
Methods
• JSP offerssame versatility that you have with java programs, such as defining methods
that are local to JSP program. A method defined, is similar to how a method is defined
in a java program except the method definition is placed within a JSP tag.
<html>
<head>
<meta charset="ISO-8859-1">
<title>Method Example</title>
</head>
<body>
<%! int square(int num)
{
return num*num ;
}
%>
<p>Square is: <%=square(12)%></p>
</body>
</html>
25.
Method Overloading
<html>
<head>
<meta charset="ISO-8859-1">
<title>Inserttitle here</title>
</head>
<body>
<%! float add(float num1, float num2)
{
return num1+num2 ;
}
int add(int num1, int num2)
{
return num1+num2;
}
%>
<p>Square is: <%=add(122,345)%></p>
<p>Square is: <%=add(145,145)%></p>
</body>
</html>
26.
Control Statements
• Theflow of control can be changed using two control statements i.e if and
switch.
<html>
<head>
<meta charset="ISO-8859-1">
<title>If Statement Example</title>
</head>
<body>
<%! int day = 3; %>
<% if (day == 1 || day == 7) { %>
<p> Today is weekend</p>
<% } else { %>
<p> Today is not weekend</p>
<% } %>
</body>
</html>
27.
<html><head><meta charset="ISO-8859-1">
<title>Insert titlehere</title></head>
<body>
<%! int day = 3; %>
<% switch(day) {
case 0:
out.println("It's Sunday.");
break;
case 1:
out.println("It's Monday.");
break;
case 2:
out.println("It's Tuesday.");
break;
case 3:
out.println("It's Wednesday.");
break;
case 4:
out.println("It's Thursday.");
break;
case 5:
out.println("It's Friday.");
break;
default:
out.println("It's Saturday.");}%>
</body></html>
28.
Loops
Three types ofloops in JSP: while, do-while and forloop
<%! int fontSize; %>
<html>
<head><title>FOR LOOP Example</title></head>
<body>
<%for ( fontSize = 1; fontSize <= 3; fontSize++){ %>
<font color = "green" size = "<%= fontSize %>">
JSP Tutorial
</font><br />
<%}%>
</body>
</html>
JSP - ImplicitObjects
JSP Implicit Objects are the Java objects that the JSP Container makes
available to developers in each page and developer can call them
directly without being explicitly declared. JSP Implicit Objects are also
called pre-defined variables.
32.
The request Object:
•The request object is an instance of a
javax.servlet.http.HttpServletRequest object. Each time a client
requests a page the JSP engine creates a new object to represent
that request.
• The request object provides methods to get HTTP header
information including form data, cookies, HTTP methods etc
33.
The response Object:
•The response object is an instance of a
javax.servlet.http.HttpServletResponse object. Just as the server
creates the request object, it also creates an object to represent the
response to the client.
• The response object also defines the interfaces that deal with
creating new HTTP headers. Through this object the JSP
programmer can add new cookies or date stamps, HTTP status
codes etc.
34.
The out Object:
•The out implicit object is an instance of a
javax.servlet.jsp.JspWriter object and is used to send content in a
response.
• The initial JspWriter object is instantiated differently depending on
whether the page is buffered or not. Buffering can be easily turned
off by using the buffered='false' attribute of the page directive.
• The JspWriter object contains most of the same methods as the
java.io.PrintWriter class. However, JspWriter has some additional
methods designed to deal with buffering. Unlike the PrintWriter
object, JspWriter throws IOExceptions.
35.
Sl.No. Method Description
1out.print(dataType dt) Print a data type value
2 out.println(dataType dt)
Print a data type value then terminate
the line with new line character.
3 out.flush() Flush the stream.
Following are the important methods which isuse to write
boolean char, int, double, object, String etc.
36.
The session Object:
•The session object is an instance of
javax.servlet.http.HttpSession and behaves exactly the same
way that session objects behave under Java Servlets.
37.
JSP Form Processing
•Get method():- The GET method sends the encoded user information
appended to the page request. The page and the encoded information are
separated by the ? character as follows:
• http://www.test.com/hello?key1=value1&key2=value2
• The GET method is the defualt method to pass information from browser to
web server and it produces a long string that appears in your browser's
Location:box.
• Never use the GET method if you have password or other sensitive
information to pass to the server. The GET method has size limtation: only
1024 characters can be in a request string.
• This information is passed using QUERY_STRING header and will be
accessible through QUERY_STRING environment variable which can be
handled using getQueryString() and getParameter() methods of request
object.
38.
Get Method withoutusing Form
<html>
<head>
<meta charset="ISO-8859-1">
<title>GetMethod Without Form</title>
</head>
<body>
<center>
<h1>Using GET Method to Read Form Data</h1>
<ul> <li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%> </p></li>
</ul>
</body>
</html>
Type below to run
http://localhost:8081/JSPGetMethodDemo/GetMethod.jsp?
first_name=chaithra&last_name=hirematt
39.
Get Method usingform
<html>
<head>
<meta charset="ISO-8859-1">
<title>GetMethod Using Form</title>
</head>
<body>
<form action="GetUsingForm.jsp" method="GET">
First Name: <input type="text" name="first_name"> <br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
40.
HTML form tocall jsp using get method
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="GetUsingForm.jsp" method="GET">
First Name: <input type="text" name="first_name"> <br
/>
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" /> </form>
</body>
</html>
41.
POST method():- orParsing other information
• A generally more reliable method of passing information to a
backend program is the POST method.
• This method packages the information in exactly the same way as
GET methods, but instead of sending it as a text string after a ? in
the URL it sends it as a separate message. This message comes to
the backend program in the form of the standard input which you
can parse and use for your processing.
• JSP handles this type of requests using getParameter() method to
read simple parameters and getInputStream() method to read
binary data stream coming from the client.
42.
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert titlehere</title>
</head>
<body>
<h1>Using POST Method to Read Form Data</h1>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
43.
HTML Form forboth get and post method
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Post Method to read Form data</title>
</head>
<body>
<form action="PostMethod.jsp" method="POST">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
44.
Request String
• ReadingForm Data using JSP
• JSP handles form data parsing automatically using the following methods
depending on the situation:
• getParameter(): You call request.getParameter() method to get the value
of a form parameter.
• getParameterValues(): Call this method if the parameter appears more
than once and returns multiple values, for example checkbox.
• getParameterNames(): Call this method if you want a complete list of all
parameters in the current request.
• getInputStream(): Call this method to read binary data stream coming
from the client.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>ReadingData using Getparameter</title>
</head>
<body>
<center>
<h1>Reading Checkbox Data using get parameter</h1>
<ul> <li><p><b>Maths Flag:</b>
<%= request.getParameter("maths")%> </p></li>
<li><p><b>Physics Flag:</b>
<%= request.getParameter("physics")%> </p></li>
<li><p><b>Chemistry Flag:</b>
<%= request.getParameter("chemistry")%> </p></li>
</ul>
</body>
</html>
47.
User Session
• AJSP Programs must be able to track a session as client moves
between HTML pages and JSP programs.
• Three commonly used method to track session.
Using hidden field: a field in which value is not displayed on
HTML page.
Using cookie
Using javaBean
48.
Cookies
• Cookie isa small piece if information created by a JSP program that is
stored on the client’s machine by the browser. It can store user
preferences and ID that track session with JSP database system.
Setting Cookies with JSP
Step 1: Creating a Cookie object
• You call the Cookie constructor with a cookie name and a cookie
value, both of which are strings.
Cookie cookie = new Cookie("key","value");
49.
Step 2: Settingthe maximum age
• You use setMaxAge to specify how long (in seconds) the
cookie should be valid. The following code will set up a
cookie for 24 hours.
cookie.setMaxAge(60*60*24);
Step 3: Sending the Cookie into the HTTP response headers
• You use response.addCookie to add cookies in the HTTP
response header as follows
response.addCookie(cookie);
50.
Setting a CookiesetCokkie.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action = "SetCookie.jsp" method = "GET">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
51.
<!DOCTYPE html>
<%
// Createcookies for first and last names.
Cookie firstName = new Cookie("first_name",
request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name",
request.getParameter("last_name"));
// Set expiry date after 24 Hrs for both the cookies.
firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);
// Add both the cookies in the response header.
response.addCookie( firstName );
response.addCookie( lastName );
%>
SetCookie.JSP continued…
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert titlehere</title>
</head>
<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookie cookie = null;
Cookie[] cookies = null;
// Get an array of Cookies associated with the this domain
cookies = request.getCookies();
if( cookies != null ) {
out.println("<h2> Found Cookies Name and Value</h2>");
for (int i = 0; i < cookies.length; i++) {
cookie = cookies[i];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
} else {
out.println("<h2>No cookies founds</h2>");
}
%>
</body>
</html>
ReadCookies.JSP
For reading Cookie
54.
Session Objects
• AJSP database system is able to share information among JSP
programs within a session by using a session object. Each time a
session is created a unique ID is assigned to the session and stored as
cookie.
• Along with session ID a session object is also used to store other types
of information called attributes.
• An attribute can be login information, preferences or even purchases
in shopping cart.