0% found this document useful (0 votes)
22 views37 pages

JSP Material SP

Uploaded by

nanipavan830
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views37 pages

JSP Material SP

Uploaded by

nanipavan830
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

JSP Directives

Description

JSP Directives have the mechanisms to interact with the JSP Container about translation of JSP
to Servlet code and how it complies JSP page. The entire JSP page process is controlled by this
directive tags. These directives do not appear in the XML output. JSP Directives has
been categorized into three types as follows.

 Page directive

 Include directive

 Taglib directive

Syntax

<%@ directive attribute=”value” %>

Conceptual
Figure

JSP Page Directive

Description

JSP Directives – Page directive has the component such that it tells the JSP container to compile
the current JSP page. This page order code is at the highest point of the JSP page. One can get to
various traits that are in JSP page by utilizing JSP page directive. These characteristics have
process the data to the JSP motor and give the guidelines while handling.

Syntax
<%@ page attribute = “true”%>

Attributes

For defining attributes two methods are followed.

1.Defining tag handler in tag class.

2.Defining tag element inside tag element.

 ContentType

 Import

 Extends

 Info

 AutoFlush

 Buffer

 IsELIgnored

 IsThreadSafe

 ErrorPage

 IsErrorPage

 Session

 Language

JSP Page: import

Description

Import is one of the most important element in the page directive. JSP container is instructed to
import other Java classes and to provide interface for generating the servlet code. It is same as
import statement of java classes. More than one package can be used for this import tag which
makes it very useful. Use of the import attribute takes one of the following two forms.

<%@ page import=”package.class1,…,package.classN” %>


<%@ page import=”package.class” %>
Example

Text.jsp

<html>

<body>

<%@ page import="java.util.Date" %>

Today is: <%= new Date() %>

</body>

</html>

Here imported the java.util.Data package that displays date.

Output

Output will be as follows, where time and date were printed.

JSP Page: contentType

Description

The contentType attribute is nothing but setting the character encode for the JSP page and
to generate response on the page which is displayed to the user. The default content type
is text/HTML. Use of the contentType attribute takes one of the following two forms.
<%@ page contentType=”MIME-Type; charset=Character-Set” %>
<%@ page contentType=”MIME-Type” %>
Syntax

<%@ page contentType=”text/html” %>

JSP Page: info

Description

The info attribute is used to the set the servlet description of the JSP page which is retrieved by
using Servlet interface getServletInfo() method.

Syntax

<%@ page info=”This JSP Page is written by SPLessons” %>

JSP Page: extends

Description

Extends attribute is used to inherit the properties of super class by generating Servlet code.This
attribute is rarely used.

Syntax

<%@ page extends=”Package_name.Class_name” %>

JSP Page: buffer

Description

The buffer attribute is used to buffer characters for the response object.If buffer value is given as
“none”, then it specifies no buffering. So that Servlet output is directed to write into response
object. If buffer value gives maximum size in kilobytes, then it directs the servlet output write
into the buffer before writing in response object. The default size is 8kb.Use of this attribute
takes one of two forms:
<%@ page buffer=”sizekb” %>
<%@ page buffer=”none” %>

Syntax

Servlet output written into buffer before writing into the response object.

<%@ page buffer=”none” %>

JSP Page: autoFlush

Description

The autoFlush attribute of a page is set to true by default. When buffer is filled, flush out occurs
automatically which is not a problem for the programmer. If autoFlush attribute is set to false,
the programmer explicitly calls flush when the buffer is filled. In case, buffer is filled before
programmer did not call flush explicitly, container raises an exception. Use of this attribute takes
one
of the following two forms.

<%@ page autoFlush=”true” %> <%– Default –%>


<%@ page autoFlush=”false” %>

Syntax

<%@ page buffer=”16kb” autoFlush=”true” %>

JSP Page: isELIgnored

Description

IsELIgnored is used to access the variable using JavaBean. This expression language supports
JSP 2.0 technology. The EL comes with expression language. The ELIgnored expression
attribute tells the container whether to execute or evaluate. Use of this attribute takes one of the
following two forms.

<%@ page isELIgnored=”false” %>


<%@ page isELIgnored=”true” %>
Syntax

<%@ page autoFlush=”true” %>

The EL expression is ignored,

<%@ page autoFlush=”false” %>

If isELIgnored = “false”, The EL expression is evaluated.


By default, server value is “true”. While using EL in JSP, server value should be set to “false”.

JSP Page: isThreadSafe

Description

IsThreadSafe attribute takes the boolean true or false to indicate that JSP and servlet both are
multi threaded. Use of the isThreadSafe attribute takes one of the following two forms.
<%@ page isThreadSafe=”true” %> <%– Default –%>
<%@ page isThreadSafe=”false” %>

Syntax

The default value of isThreadSafe is true which means each client is served with separate
_jspService() method to the same JSP.

<%@ page isThreadSafe=”true” %>

If threadSafe is false, multiple client requests to the same JSP. Second request is processed only
after the first request response is occured. Till then second request has to wait.

<%@ page isThreadSafe=”false” %>

JSP Page: errorPage

Description

ErrorPage attribute is used to handle the exception for the current page and has a mechanism to
forward the current page exception to other pages. This page directive should be used at the
beginning of the JSP page.
Syntax

<%@ page errorPage=”ErrorPage_name.jsp” %>

JSP Page: isErrorPage

Description

IsErrorPage attribute sets the value to true. It has the capability to receive the exception from
the other page. Implicit object exception is available on this page only when the value is set to
true. But the default value is false. Use of isErrorPage takes one of the following two forms:
<%@ page isErrorPage=”true” %>
<%@ page isErrorPage=”false” %> <%– Default –%>

Syntax

<%@ page isErrorPage=”false” %>

JSP Page: language

Example

Language attribute indicates the scripting language and is used in the JSP. The default language
is “Java“.

Syntax

<%@ page language=”java” %>

JSP Page: session

Description

JSP Directives – Session attribute is used to check whether session is created or not. If declared
session value is false, then session is not created by container. Else the session is created by
making the value to true. Use of this attribute takes one of the following two forms.
<%@ page session=”true” %> <%– Default –%>
<%@ page session=”false” %>

Syntax

<%@ page session=”true” %>

JSP Include Directive

Description

Using JSP include directory others files can be included in the JSP. The included file can be
HTML, Java, Text file. Using include directory template for user view can be created.

JSP TaglibDirective

Description

JSP Directives – Tablib directive basically allows user to use Custom tags in JSP. JSP taglib
directive is used for defining a tag library with prefix which can be used in JSP.

Summary

Key Points

 JSP include directory is used to include another JSP file.

 Custom tags can be used.

 JSP Directives import attribute is used to inherit classes and interfaces.

 JSP Directives extends attribute is used to inherit the parent class properties.
JSP Scriptlet

Introduction

JSP Scriptlet- Basically writing Java code in HTML tags is very difficult. In JSP, script tag is
used to write JAVA related code within a JSP page. For use scriptlet tags, scripting elements
must be known. Java code can be kept between. A scriptlet is a valid code in Java and is put into
the jspService () method of the JSP engine at the time of running. The Scripting elements are
written in Java code in the JSP page. Object creation and accessing will be done by elements of
the script.

Following are the types of Scripting Elements

1. Expression Tag

2. Declaration Tag

3. Scriptlet Tag

Conceptual
figure

JSP Scripting Tag

Description

 The Java code written in a scriptlet tag goes to _jspService () method of a JSP that is
equivalent to servlet program.

 Business logic or requesting processing logic code can be placed in the scriptlet tag of
JSP program.

 In a scriptlet tag, implicit objects are visible and used to perform JSP related programs.
 Variables will be initialized in JSP as a local variables of _jspService() method in JSP
program.

Syntax

<% java code %>

JSP Expression Tag

Description

To read the values of any functions like methods or variables Expression Tag will be used,
out.print() used to read the information in expression tag.

Syntax

<%= java expression %>

JSP Declaration Tag

Description

In declaration tag methods, varaiables can be declared. Static functions and instance variables
can be declared.

Syntax

<%! declaration %>

Example

Following is an example by using syntax.

index.jsp

<html>

<body>

<h2>

<% int a=20; int b=10; int c = a+b; out.println("result is :" +c); %>

</h2>

</body>
</html>

Output:
Here the developer used three variables a, b, c where c is used to add two values.

compare.jsp

<% int a = 20; int b = 10; if(a>b)

out.println("a is bigger");

else

out.println("b is bigger");

%>

Output:
It displays the bigger element.

Summary

Key Points

 JSP Scriptlet – Scriplet tag is used for executing java code in JSP.

 JSP Scriptlet – Scriptlet tags are easy to write.

 JSP Scriptlet – out.println() is used for scripting languages


JSP Implicit Objects

Description

JSP Implicit Objects, JSP has 9 implicit objects made by web container and those implicit
objects are available in all JSP pages. Implicit objects can be directly used in scriptlets. JSP
Implicit objects can be directly used without declaring.

 Out

 Page

 Page Context

 Exception

 Config

 Application

 Session

 Request

 Response

Conceptual
figure
Page

Page is an implict object. Page object is used for referencing auto generated Servlet class. For
using page object type casting must be done.

Out

Out object is used for writing data into buffer. Out object belongs to JspWriter. Out object is
mostly used with JspExpression to invoke the class.

Request

Request is an implict object of HttpServletRequest. Request object is used for requesting


parameters, character encoding, header type, content, information, remote address, server name,
server port.

Exception

Exception object is typically utilized for producing a suitable reaction to the mistake condition.

Page Content

The pageContext is utilized to indicate the whole JSP page. PageContext object is an instance of
a javax.servlet.jsp.PageContext.PageContent object is used as a way to get to data about the page
while concealing a large portion of the execution points of interest.

Config

This object is utilized to get introduction parameter for a specific JSP page and it is made to
every single JSP page.

Response

Response object is used for providing methods to the HTML header. Responce object is implict
of javax.servlet.http.HttpServletRequest.

Session

Session object is associated with HTTP Request. Session object is for set, get or remove attribute
or to get session information.

Application
It is an instance of a javax.servlet.ServletContext. Application object is created by web container.
Application object is also used to get RequestDispatcher object.

List of JSP Implicit Objects

Table

Object Package Scope

application Javax.servlet.ServletContext Web application scope

exeption Javax.servlet.Throwable page scope

page This(current class object reference) page scope

config Javax.servlet.ServletConfig Page Scope

out javax.servlet.jsp.jspwriter page scope

pagecontext java.servlet.jsp.PageContext page scope

session javax.servlet.http.HttpSession Session scope

request javax.servlet.http.HttpServletRequest Request scope

response javax.servlet.hht.HttpServletRespons Response scope

JSP Implicit Object: Out

Description

JSP Implicit Objects – While writing the JSP program, it is not possible to remember the class
names of the implicit objects because the change is based on the server utilized.

The implicit out is an object of JSP container, which supplies java class that extends
from javax.servlet.jsp.JspWriter, and not directly from the javax.servlet.jsp.JspWriter class.

Example

Following is an example.
welcome.jsp

<html>
<body>

<% out.println("Hi john, welcome to Splessons"); %>

</body>

</html>

Output
Here out.println is used to display the data.

Summary

Key Points

 JSP Implicit Objects can be also called as pre defined variables.

 Implict objects are Java objects and they are placed in Jsp Container.

JSP Forms
Description

JSP Forms, Working with credential applications is always a challenging task, as earlier
discussed JSP code will be combined with HTML code. While working with forms in any
technology GET and POST methods will be used, many developers will prefer POST method
why because it carries a large amount of data to the server where as GET method is the default
method. Following is an example which describes how the form application will work.

Example

Following is an example to understand the form concept.


Index.html

<html>

<body bgcolor="skyblue">

<form action="formValidation.jsp" method="GET">

<center>

<h1>Register to the SPLessons</h1>

<img src="E:/splessons.png"></br></br>

First Name: <input type="text" name="first_name"></br></br>

Last Name: <input type="text" name="last_name" /></br></br>

<input type="submit" value="Submit" /></center>

</form>

</body>

</html>

Here the developer created the two text box fields to enter the First Name, Last Name and also
created submit button. When compile the code, page will be displayed as static.

Get Method

JSP Forms – The GET method is the default method to pass data from client to web server and
it delivers a long string that shows up in the browser’s Location. Never utilize the GET method
in the event that you have secret key or other touchy data to go to the server. The GET method
has size constraint: just 1024 characters can be in a solicitation string.

Post Method

JSP Forms – A for the most part more solid method for passing data to a backend code is
the POST method. This method bundles the data in the very same route as GET strategies, yet
as opposed to sending it as a content string after a ? in the URL it sends it as a different message.
This message goes to the backend program as the standard information which one can parse and
use for preparing.
formvalidation.jsp

<html>

<body bgcolor="skyblue">

<center>

<h1>Welcome to the Splessons</h1></br></br>

<b>First Name:</b><%= request.getParameter("first_name")%><br/>

<b>Last Name:</b><%= request.getParameter("last_name")%></br></br>

Visit <a href="http://www.splessons.com/">splesson.com</a></center>

</body>

</html>

request.getparameter() is used to get the First Name and Last Name.

Output
When compile the program following is the output will be displayed where enter the details.
When click on submit button following output will be displayed.
Summary

Key Points

 JSP Forms – request.getParameter is utlized to retrieve the data

 JSP Forms – POST requests can not be book marked.

 Get method is the default method.


JSP Cookies

Description

JSP Cookies – Cookies can defined as a small file that will be stored in a browser, it is utilized
information tracing purpose. Already Splessons have discussed the cookies concept in servlet
technology Servlet Cookies. Following is the list of important useful methods associated with the
Cookie object which you can use while manipulating cookies in JSP.

 public void setDomainStringpattern

 public String getDomain

 public String getName

 public String getValue

 public String getPath

 public String getComment

Example

JSP Cookies – Following is the example which describes more about the cookies. Following is
the code to set the cookies.
index.jsp

<html>

<body bgcolor="skyblue">

<form action="main.jsp" method="GET">

<center><img src="E:/splessons.png"></br></br>

First Name: <input type="text" name="first_name"></br>

<br />

Last Name: <input type="text" name="last_name"/></br></br>

<input type="submit" value="Submit" /></center>

</form>
</body>

</html>

Here just created two forms they are First Name, Last Name and also created Submit button.
The GETmethod is the default method to pass data from client to web server and it delivers a
long string that shows up in the browser’s Location. Never utilize the GET method in the event
that you have secret key or other touchy data to go to the server. The GET method has size
constraint: just 1024 characters can be in a solicitation string.
main.jsp

<%

// Create cookies 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 );

%>

<html>

<head>

<title>Setting Cookies</title>

</head>

<body>

<center>
<h1>Setting Cookies</h1>

</center>

<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>

The request.getParameter() is used to retrieve the details from the static page that
id HTML page.
Output
When compile the code following is the output will be displayed.
When submit the details final result will be come.

Following is an example to read the cookies with JSP. keep the following code in main.jsp file.

<html>

<head>

<title>Reading Cookies</title>

</head>

<body>
<center>

<h1>Reading Cookies</h1>

</center>

<%

Cookie cookie = null;

Cookie[] cookies = null;

// Get an array of Cookies associated with 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>

Place this code in the place of main.jsp file. request.getCookies() is used to get the cookies.
Output
When compile the code following is the output will be displayed.
Following is the code to delete the cookies. Keep the following code in main.jsp file.

<html>

<head>

<title>Reading Cookies</title>

</head>

<body>

<center>

<h1>Reading Cookies</h1>

</center>

<%

Cookie cookie = null;

Cookie[] cookies = null;

// Get an array of Cookies associated with 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];

if((cookie.getName( )).compareTo("first_name") == 0 ){

cookie.setMaxAge(0);

response.addCookie(cookie);

out.print("Deleted cookie: " +

cookie.getName( ) + "<br/>");

out.print("Name : " + cookie.getName( ) + ", ");

out.print("Value: " + cookie.getValue( )+" <br/>");

}else{

out.println(

"<h2>No cookies founds</h2>");

%>

</body>

</html>

public void setMaxAge(int expiry) method sets how much time (in seconds) should elapse
before the cookie expires. If you don’t set this, the cookie will last only for the current session.
Output
When compile the code following is the output will be diplayed, where first name will deleted as
mentioned in the code.
Summary

Key Points

 JSP Cookies – To read cookies, you need to create an array of Java. servlet. http. Cookie
objects by calling the GetCookies method of HttpServletRequest.

 JSP Cookies – response.addCookie is used to add the cookie to the Http response
header.

JSP Session

Description

JSP Session is an implicit object of the type HttpSession. JSP Session object is used to send
information from the web browser to server and from the server to a web browser. The main
advantage of the Session Object is, it maintains information when there are multiple requests.
Session handling becomes important when requested data need to be sustained for further use.
When variables are stored in JSP Session object, it will navigate between multiple requests in the
application. To maintain information in entire application use
of cookies, URL rewriting, Hidden Form Fields are used.
Methods of JSP Session object

Methods

setAttribute(String, object)

setAttribute(String, object) method is used to set an object by assigning a unique string to that
object, later that object can be used anyway in the application by using the unique string.

getAttribute(String, object)

getAttribute(String) method is used to get the session which is already stored


in setAttribute() method and the return type of this method is an object.

removeAttribute(String)

removeAttribute(String) method is used to remove the session object which is stored in the
session. To pass a unique string removeAttribute’s method can be used.

getAttributesNames()

getAttributesNames() method is used to return all the objects which are stored in the session.
getId()

getId() method returns the unique string identifier from a session in which servlet container is
assigned.

getCreationTime()

getCreationTime() method is used when a session is initialized and returns session creation time.

isNew()

isNew() method checks whether a session is new or not, If a session is new it returns true
otherwise false.

invalidate()

invalidate() method is used for making session inactive and breaks the session with stored object.

getLastAccessedTime()

getLastAccessedTime() method returns the session last access time.

getMaxInactiveInterval()

getMaxInactiveInterval() method returns maximum inactive time of session.

JSP Session Object

Example

JSP Session – Following is an example.

index1.html

<html>

<body>

<form action="welcome1.jsp">

<input type="text" name="uname">

<input type="submit" value="go"><br/>

</form>

</body>
</html>

Here just created the text box and also created the go button.
welcome1.jsp

<html>

<body>

<%

String name=request.getParameter("uname");

out.print("Welcome "+name);

session.setAttribute("user",name);

%>

<a href="second.jsp">second jsp page</a>

</body>

</html>

request.getParameter(“uname”) is used to get the parameters from the HTML page.


second.jsp

<html>

<body>

<%

String name=(String)session.getAttribute("user");

out.print("Hello "+name);

%>

</body>

</html>

While executing the code index1.html file should be in active mode.

Output:
After executing the above code successfully,where first write the text as like to
SPLESSONS then click on go button.

Output will be as follows along with the second.jsp file is as follows.

When click second.jsp file, output will be as follows .


Summary

Key Points

 JSP Session – The session is time oriented if time is completed, then the session will be
automatically closed.

 JSP Session – Cookies store the information in the client browser.

 JSP Session is an implicit object of the type HttpSession.

 The JSP Session object provides the communication between the server and browser to
fetch the data.

JSP Session Tracking

Description

JSP Session Tracking – If a web application is capable of remembering a client data during a
session across the multiple requests then that web application is called as a stateful Web
application. Even though HTTP is a stateless protocol, web applications should be made as
stateful web applications. For this, working with the following session tracking or session
management techniques is necessary.

 Hidden Form fields

 HTTP Cookies

 Session ID

 HTTP session with URL rewriting

Hidden Form Fields

JSP Session Tracking – A web server can send a hidden HTML structure field alongside a
unique session ID as follows.

<input type="hidden" name="sessionid" value="54321">

at the point when the form is presented, the predetermined name and value are consequently
incorporated into the GET or POST information. Every time when web program sends request
back, then session_id value can be utilized to monitor distinctive web programs.
Cookies

JSP Session Tracking – A webserver can relegate a one of a kind session ID as a treat to every
web browser and for resulting requests from the client they can be perceived utilizing the got
cookie. This may not be a successful way on the grounds that numerous time program does not
bolster a cookie.

URL Rewriting

JSP Session Tracking – One can add some additional information on the end of every URL that
distinguishes the session, and the server can relate that session identifier with information it has
put away about that session. URL Rewriting is a superior approach to keep up sessions and
works for the programs when they don’t support cookies yet here downside is that you would
have produce each URL powerfully to allocate a session ID however page is basic static HTML
page.

Session Object

JSP Session Tracking – JSP makes utilization of servlet gave HttpSession Interface which gives
an approach to distinguish a client crosswise over more than one page request or visit to a Web
webpage and to store data about that client.

Of course, JSPs have session tracking empowered and another HttpSession object is instantiated
for each new client consequently. Incapacitating session following requires unequivocally
turning it off by setting the page order session credit to false as follows.

<%@ page session="false" %>

Session tracking is all about making web application as a stateful web application by
remembering client data across the multiple requests during a session. Following are the
RealTime Implementation of session tracking/session management. Following is the servlet
session tracking link.

Servlet Session Tracking

Conceptual
Figure
When the client is sending the request, server gives back response where already session will be
stored.

Example

Following is the session tracking example.


index.html

<%@ page import="java.io.*,java.util.*" %>

<%

// Get session creation time.

Date createTime = new Date(session.getCreationTime());

// Get last access time of this web page.

Date lastAccessTime = new Date(session.getLastAccessedTime());

String title = "Welcome Back to my website";


Integer visitCount = new Integer(0);

String visitCountKey = new String("visitCount");

String userIDKey = new String("userID");

String userID = new String("SPlesson");

// Check if this is new comer on your web page.

if (session.isNew()){

title = "Welcome to SPlessons";

session.setAttribute(userIDKey, userID);

session.setAttribute(visitCountKey, visitCount);

visitCount = (Integer)session.getAttribute(visitCountKey);

visitCount = visitCount + 1;

userID = (String)session.getAttribute(userIDKey);

session.setAttribute(visitCountKey, visitCount);

%>

<html>

<head>

<title>Session Tracking</title>

</head>

<body bgcolor ="skyblue">

<center>

<img src="E:/splessons.png"></br>

<h1>Session Tracking</h1>

</center>
<table border="1" align="center">

<tr bgcolor="#949494">

<th>Session info</th>

<th>Value</th>

</tr>

<tr>

<td>id</td>

<td><% out.print( session.getId()); %></td>

</tr>

<tr>

<td>Creation Time</td>

<td><% out.print(createTime); %></td>

</tr>

<tr>

<td>Time of Last Access</td>

<td><% out.print(lastAccessTime); %></td>

</tr>

<tr>

<td>User ID</td>

<td><% out.print(userID); %></td>

</tr>

<tr>

<td>Number of visits</td>

<td><% out.print(visitCount); %></td>

</tr>
</table>

</body>

</html>

In this code, when compile the code page will be displayed on he browser, if user refresh the
page number of counts will be increased. Where the developer used visitCount.
When compile the code following is the code will be displayed.

Summary

Key Points

 In the URL phase developer can add a little data to identify the session like
sessionid=123.

 The web server has the ability to send the hidden HTML data along with the session id.

You might also like