JSP Topic
JSP Topic
jsp:useBean
2
Finds or instantiates a JavaBean.
jsp:setProperty
3
Sets the property of a JavaBean.
jsp:getProperty
4
Inserts the property of a JavaBean into the output.
jsp:forward
5
Forwards the requester to a new page.
jsp:plugin
6
Generates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin.
jsp:element
7
Defines XML elements dynamically.
jsp:attribute
8
Defines dynamically-defined XML element's attribute.
jsp:body
9
Defines dynamically-defined XML element's body.
jsp:text
10
Used to write template text in JSP pages and documents.
Common Attributes
• There are two attributes that are common to all Action elements:
the id attribute and the scope attribute.
• Id attribute
• The id attribute uniquely identifies the Action element, and allows the action to
be referenced inside the JSP page. If the Action creates an instance of an object,
the id value can be used to reference it through the implicit object PageContext.
• Scope attribute
• This attribute identifies the lifecycle of the Action element. The id attribute and
the scope attribute are directly related, as the scope attribute determines the
lifespan of the object associated with the id. The scope attribute has four
possible values: (a) page, (b)request, (c)session, and (d) application.
<jsp:include> Action
• This action lets you insert files into the page being
generated. The syntax looks like this −
• <jsp:include page = "relative URL" flush = "true" />
• Unlike the include directive, which inserts the file at the
time the JSP page is translated into a servlet, this action
inserts the file at the time the page is requested.
• Following table lists out the attributes associated with the
include action −
S.No. Attribute & Description
page
1 The relative URL of the page to
be included.
flush
The boolean attribute determines
2 whether the included resource
has its buffer flushed before it is
included.
• Let us define the following two files (a)date.jsp and (b) main.jsp as follows −
• Following is the content of the date.jsp file −
• <p>Today's date:
• <%= (new java.util.Date()).toLocaleString()%>
• </p>
• Let us define the following two files (a)date.jsp and (b) main.jsp as follows −
• <p>Today's date:
• <%= (new java.util.Date()).toLocaleString()%>
• </p>
• Following is the content of the main.jsp file −
<html>
<head>
<title>The include Action Example</title>
</head>
<body>
<center>
<h2>The include action Example</h2>
<jsp:include page = "date.jsp" flush = "true" /> </center>
</body>
</html>
<jsp:useBean> Action
• The useBean action is quite versatile. It first searches for an
existing object utilizing the id and scope variables. If an
object is not found, it then tries to create the specified object.
• The simplest way to load a bean is as follows −
• <jsp:useBean id = "name" class = "package.class" />
• Once a bean class is loaded, you can
use jsp:setProperty and jsp:getProperty actions to modify
and retrieve the bean properties.
S.No. Attribute & Description
class
1 Designates the full package name of
the bean.
type
2 Specifies the type of the variable that
will refer to the object.
beanName
Gives the name of the bean as specified
3
by the instantiate () method of the
java.beans.Beans class.
• Let us now discuss the jsp:setProperty and the jsp:getProperty actions before giving a valid example related to these
actions.
• The <jsp:setProperty> Action
• The setProperty action sets the properties of a Bean. The Bean must have been previously defined before this action.
• There are two basic ways to use the setProperty action −
• You can use jsp:setProperty after, but outside of a jsp:useBean element, as given below
−
• <jsp:useBean id = "myName" ... /> ...
• <jsp:setProperty name = "myName" property = "someProperty" .../>
• In this case, the jsp:setProperty is executed regardless of whether a new bean was
instantiated or an existing bean was found.
• A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as given below −
• <jsp:useBean id = "myName" ... > ... <jsp:setProperty name = "myName" property = "someProperty" .../>
• </jsp:useBean>
• Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was found.
The <jsp:getProperty> Action
name
The name of the Bean that has a
1
property to be retrieved. The Bean
must have been previously defined.
property
The property attribute is the name
2
of the Bean property to be
retrieved.
• Example
• Let us define a test bean that will further be used in our example −
• /* File: TestBean.java */
package action;
public class TestBean
{
private String message = "No message specified";
public String getMessage()
{
return(message);
}
public void setMessage(String message)
{
this.message = message;
} }
<html>
<head>
<title>Using JavaBeans in JSP</title>
</head>
<body>
<center>
<h2>Using JavaBeans in JSP</h2>
<jsp:useBean id = "test" class = "action.TestBean" />
<jsp:setProperty name = "test" property = "message" value = "Hello JSP..." />
<p>Got message....</p>
<jsp:getProperty name = "test" property = "message" />
</center>
</body>
</html>
<jsp:forward> Action
• The forward action terminates the action of the current page and forwards the request to another resource such as a static page,
another JSP page, or a Java Servlet.
• Following is the syntax of the forward action −
• <jsp:forward page = "Relative URL" />
• The plugin action is used to insert Java components into a JSP page. It determines the type of
browser and inserts the <object> or <embed> tags as needed.
• If the needed plugin is not present, it downloads the plugin and then executes the Java component.
The Java component can be either an Applet or a JavaBean.
• The plugin action has several attributes that correspond to common HTML tags used to format Java
components. The <param> element can also be used to send parameters to the Applet or Bean.
• <jsp:plugin type = "applet" codebase = "dirname" code = "MyApplet.class" width = "60" height =
"80">
• <jsp:param name = "fontcolor" value = "red" />
• <jsp:param name = "background" value = "black" /> <jsp:fallback> Unable to initialize Java Plugin
</jsp:fallback>
• </jsp:plugin>
<jsp:text> Action
• The <jsp:text> action can be used to write the template text in JSP pages and
documents.
• Following is the simple syntax for this action −
• <jsp:text>Template data</jsp:text>
• The body of the template cannot contain other elements; it can only contain text and
EL expressions Note that in XML files, you cannot use expressions such as $
{whatever > 0},
• because the greater than signs are illegal.
• Instead, use the gt form, such as ${whatever gt 0} or an alternative is to embed the
value in a CDATA section.
• <jsp:text><![CDATA[<br>]]></jsp:text>
Implicit objects
• These Objects are the Java objects that the JSP Container
makes available to the developers in each page and the
developer can call them directly without being explicitly
declared. JSP Implicit Objects are also called pre-defined
variables.
S.No. Object & Description
request
1
This is the HttpServletRequest object associated with the request.
response
2
This is the HttpServletResponse object associated with the response to the client.
out
3
This is the PrintWriter object used to send output to the client.
session
4
This is the HttpSession object associated with the request.
application
5
This is the ServletContext object associated with the application context.
config
6
This is the ServletConfig object associated with the page.
pageContext
7
This encapsulates use of server-specific features like higher performance JspWriters.
page
8 This is simply a synonym for this, and is used to call the methods defined by the
translated servlet class.
Exception
9
The Exception object allows the exception data to be accessed by designated JSP.
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 the HTTP header information including form
data, cookies, HTTP methods etc.
• Custom tags are user-defined tags. They eliminates the possibility of scriptlet tag and separates
the business logic from the JSP page.
• The same business logic can be used many times by the use of custom tag.
• Syntax to use custom tag:
• There are two ways to use the custom tag. They are given below:
• <prefix:tagname attr1=value1....attrn=valuen />
• <prefix:tagname attr1=value1....attrn=valuen >
• body code
• </prefix:tagname>
JSP Custom Tag API
• The JspTag is the root interface for all the interfaces and
classes used in custom tag. It is a marker interface.
• Tag interface
• The Tag interface is the sub interface of JspTag interface.
It provides methods to perform action at the start and end
of the tag.
IterationTag interface
• The TagSupport class implements the IterationTag interface. It acts as the base class for new Tag Handlers. It
provides some additional methods also.
• Let's use the tag in our jsp file. Here, we are specifying
the path of tld file directly. But it is recommended to use
the uri name instead of full path of tld file. We will learn
about uri later.
• It uses taglib directive to use the tags defined in the tld
file.
Object scope:
• The availability of a JSP object for use from a particular place of the application is defined as the scope of that JSP object. Every object
created in a JSP page will have a scope. Object scope in JSP is segregated into four parts and they are page, request, session and
application.
• page
‘page’ scope means, the JSP object can be accessed only from within the same page where it was created. The default scope for JSP
objects created using <jsp:useBean> tag is page. JSP implicit objects out, exception, response, pageContext, config and page have ‘page’
scope.
• request
A JSP object created using the ‘request’ scope can be accessed from any pages that serves that request. More than one page can serve a
single request. The JSP object will be bound to the request object. Implicit object request has the ‘request’ scope.
• session
‘session’ scope means, the JSP object is accessible from pages that belong to the same session from where it was created. The JSP object
that is created using the session scope is bound to the session object. Implicit object session has the ‘session’ scope.
• application
A JSP object created using the ‘application’ scope can be accessed from any pages across the application. The JSP object is bound to the
application object. Implicit object application has the ‘application’ scope.
Synchronization issues:
• Synchronization in Java is a critical concept in
concurrent programming that ensures multiple threads
can interact with shared resources safely. In a nutshell,
synchronization prevents race conditions, where the
outcome of operations depends on the timing of thread
execution. It is the capability to control the access of
multiple threads to any shared resource. Synchronization
is a better option where we want to allow only one thread
to access the shared resource.
Key synchronization issues :
• Race Conditions:
• When the outcome of an operation depends on the unpredictable timing of multiple threads accessing shared data, potentially leading to
inconsistent results.
• Data Corruption:
• Occurs when one thread reads a shared variable while another is modifying it, resulting in incomplete or inaccurate data.
• Deadlocks:
• A situation where two or more threads are waiting for each other to release resources they need to proceed, causing the application to freeze.
• Livelock:
• When threads continuously switch between states without making any progress due to conflicting actions.
• Improper Lock Granularity:
• Using too broad synchronization (locking large portions of code) can unnecessarily restrict concurrency and impact performance.
• Visibility Issues:
• When changes made by one thread are not immediately visible to other threads due to cache incoherence, leading to inconsistent data reads.
Session management:
• Session is used to save user information momentarily on the
server. It starts from the instance the user logs into the
application and remains till the user logs out of the application or
shuts down the machine. In both cases, the session values are
deleted automatically. Hence, it functions as a temporary storage
that can be accessed till the user is active in the application and
can be accessed when the user requests a URI. This session is
stored in binary values, hence maintaining the security aspect,
and can be decoded only at the server end.
• What is Session Management?
• Keeping track of the user's preferences over a website or
an application as long as the user is logged into the
system for a specific time is called Session Management.
This lasts until they log out or their session expires. In
simpler terms, it's like keeping a record of user activities
when they simply surf the application so that from next
time onwards, the user doesn't have to specify the
preferences again.
Session Management/ Tracking
Methods
• Cookies:-
• A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests
from the client they can be recognized using the received cookie.
• This may not be an effective way as the browser at times does not support a cookie. It is not
recommended to use this procedure to maintain the sessions.
• Hidden Form Fields:-
• A web server can send a hidden HTML form field along with a unique session ID as follows −
• <input type = "hidden" name = "sessionid" value = "12345"> This entry means that, when the form is
submitted, the specified name and value are automatically included in the GET or the POST data. Each
time the web browser sends the request back, the session_id value can be used to keep the track of
different web browsers.
• This can be an effective way of keeping track of the session but clicking on a regular (<A HREF...>)
hypertext link does not result in a form submission, so hidden form fields also cannot support general
session tracking.
• URL Rewriting:-You can append some extra data at the end of each URL. This data identifies the session; the server can associate that
session identifier with the data it has stored about that session.
• For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session identifier is attached as sessionid = 12345 which can be
accessed at the web server to identify the client.
• URL rewriting is a better way to maintain sessions and works for the browsers when they don't support cookies. The drawback here is that
you will have to generate every URL dynamically to assign a session ID though page is a simple static HTML page.
• The session Object
• Apart from the above mentioned options, JSP makes use of the servlet provided HttpSession Interface. This interface provides a way to
identify a user across.
• a one page request or
• visit to a website or
• store information about that user
• By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each new client automatically. Disabling
session tracking requires explicitly turning it off by setting the page directive session attribute to false as follows −
• <%@ page session = "false" %>
Method & Description
• public Object getAttribute(String name)
• This method returns the object bound with the specified name in this
session, or null if no object is bound under the name.
• public Enumeration getAttributeNames()
• This method returns an Enumeration of String objects containing the
names of all the objects bound to this session.
• public long getCreationTime()
• This method returns the time when this session was created, measured
in milliseconds since midnight January 1, 1970 GMT.
• public boolean isNew()
• This method returns true if the client does not yet know about the session or if the client chooses not to join the session.
• public void removeAttribute(String name)
• This method removes the object bound with the specified name from this session.
• public int getMaxInactiveInterval()
• This method returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.
• public void invalidate()
• This method invalidates this session and unbinds any objects bound to it.
• public String getId()
• This method returns a string containing the unique identifier assigned to this session.
• public long getLastAccessedTime()
• This method returns the last time the client sent a request associated with the this session, as the number of milliseconds since midnight
January 1, 1970 GMT.
Deleting Session Data
• When you are done with a user's session data, you have several options −
• Remove a particular attribute − You can call the public void
removeAttribute(String name) method to delete the value associated with the a
particular key.
• Delete the whole session − You can call the public void invalidate() method to
discard an entire session.
• Setting Session timeout − You can call the public void setMaxInactiveInterval(int
interval) method to set the timeout for a session individually.
• Log the user out − The servers that support servlets 2.4, you can call logout to log the
client out of the Web server and invalidate all sessions belonging to all the users.
• web.xml Configuration − If you are using Tomcat, apart from the above mentioned
methods, you can configure the session time out in web.xml file as follows.
• <session-config> <session-timeout>15</session-
timeout> </session-config> The timeout is expressed as
minutes, and overrides the default timeout which is 30
minutes in Tomcat.
• The getMaxInactiveInterval( ) method in a servlet
returns the timeout period for that session in seconds. So
if your session is configured in web.xml for 15
minutes, getMaxInactiveInterval( ) returns 900.