JSP Material SP
JSP Material SP
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
Conceptual
Figure
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
ContentType
Import
Extends
Info
AutoFlush
Buffer
IsELIgnored
IsThreadSafe
ErrorPage
IsErrorPage
Session
Language
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.
Text.jsp
<html>
<body>
</body>
</html>
Output
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
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
Description
Extends attribute is used to inherit the properties of super class by generating Servlet code.This
attribute is rarely used.
Syntax
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.
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.
Syntax
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.
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.
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.
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
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
Example
Language attribute indicates the scripting language and is used in the JSP. The default language
is “Java“.
Syntax
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
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 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.
1. Expression Tag
2. Declaration Tag
3. Scriptlet Tag
Conceptual
figure
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
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
Description
In declaration tag methods, varaiables can be declared. Static functions and instance variables
can be declared.
Syntax
Example
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
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.
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
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.
Table
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>
</body>
</html>
Output
Here out.println is used to display the data.
Summary
Key Points
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
<html>
<body bgcolor="skyblue">
<center>
<img src="E:/splessons.png"></br></br>
</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>
</body>
</html>
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
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.
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">
<center><img src="E:/splessons.png"></br></br>
<br />
</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
<%
request.getParameter("first_name"));
request.getParameter("last_name"));
firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);
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>
<%
cookies = request.getCookies();
cookie = cookies[i];
}else{
%>
</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>
<%
cookies = request.getCookies();
cookie = cookies[i];
if((cookie.getName( )).compareTo("first_name") == 0 ){
cookie.setMaxAge(0);
response.addCookie(cookie);
cookie.getName( ) + "<br/>");
}else{
out.println(
%>
</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)
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()
getMaxInactiveInterval()
Example
index1.html
<html>
<body>
<form action="welcome1.jsp">
</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);
%>
</body>
</html>
<html>
<body>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>
Output:
After executing the above code successfully,where first write the text as like to
SPLESSONS then click on go button.
Key Points
JSP Session – The session is time oriented if time is completed, then the session will be
automatically closed.
The JSP Session object provides the communication between the server and browser to
fetch the data.
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.
HTTP Cookies
Session ID
JSP Session Tracking – A web server can send a hidden HTML structure field alongside a
unique session ID as follows.
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.
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.
Conceptual
Figure
When the client is sending the request, server gives back response where already session will be
stored.
Example
<%
if (session.isNew()){
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>
<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>
</tr>
<tr>
<td>Creation Time</td>
</tr>
<tr>
</tr>
<tr>
<td>User ID</td>
</tr>
<tr>
<td>Number of visits</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.