0% found this document useful (0 votes)
2 views

ch3

The document provides an overview of JSP (JavaServer Pages) and JavaBeans, covering topics such as JSP basics, advantages and disadvantages, architecture, lifecycle, and elements. It highlights the differences between JSP and Servlets, emphasizing JSP's ease of use for web design and separation of presentation from business logic. Additionally, it details JSP directives, scripting elements, and the lifecycle phases of JSP pages.

Uploaded by

vivekkanet11
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

ch3

The document provides an overview of JSP (JavaServer Pages) and JavaBeans, covering topics such as JSP basics, advantages and disadvantages, architecture, lifecycle, and elements. It highlights the differences between JSP and Servlets, emphasizing JSP's ease of use for web design and separation of presentation from business logic. Additionally, it details JSP directives, scripting elements, and the lifecycle phases of JSP pages.

Uploaded by

vivekkanet11
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

J2EE 3. JSP,Java Beans B.C.A.

SEM -5

3 JSP,Java Beans

Topics Covered
1. Introduction to JSP and JSP Basics
2. Advantages using JSP
3. Disadvantages of JSP
4. JSP Vs. Servlet
5. JSP Architecture
6. Lifecycle of JSP
7. JSP elements
8. Comments and template data
9. JSP Implicit objects
10. JSP Scope
11. Including and Forwarding from JSP Pages – Include Action , Forward Action
12. Working with Session and Cookie in JSP
13. Error Handling and Exception Handling with JSP
14. JDBC With JSP
15. JavaBean Properties
16. JavaBean Methods
17. JavaBean Packaging

1. Introduction
❖ JSP technology is used to create web application just like Servlet technology. It can be
thought of as an extension to the servlet because it provides more functionality than servlet.
❖ A JSP page contains HTML code and JSP tags. The JSP pages are easier to maintain than
servlet because we can separate designing and development. It provides some additional
features such as Expression Language, Custom Tag etc.
2. Advantages using JSP
❖ Nobody can borrow the code.
▪ The JSP code written runs and remains on the webserver so, issue of copy source
code doesn’t arise at all.
❖ Faster loading of pages.
▪ With JSP decision can be made about what user want to see at webserver prior the
page being dispatched
❖ No Browser compatibility issues
▪ The JSP page can run same way in browser the developer end-up sending standard
HTML to a user-browser.
▪ Cross browser compatibility.
❖ JSP supports
▪ JSP supported by number of webservers like Apache, Microsoft IIS, Microsoft
PWS, Netscape FastTrack and Enterprise web servers
❖ Compilation
▪ Important benefit of JSP is that it is always compiled before the webserver process
it.

Shri M M Ghodasara Mahila College,Junagadh Page 1 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5


It allows the server to handle JSP page much much faster, Because older
technologies like CGI required server to load an interpreter and the target script
each time the page is requested.
❖ Embedded with HTML- XML

▪ JSP pages looks like an HTML or XML pages, it holds text marked with collection
of tags.

3. Disadvantages of JSP
❖ Java code required
▪ Simple things in JSP actually demands putting a java code in a page.
❖ Simple tasks are hard to code
▪ Even including page header and footer is bit difficult with JSP
❖ Difficult looping in JSP
▪ In Regular JSP pages lopping is difficult, In advance JSP we can use some custom
tags for looping
❖ Occupies lot of space
▪ JSP consumes extra hard drive and memory(RAM) space
❖ As JSP pages are translated to servlets and compiled, it is difficult to trace errors occurred
in JSP pages.
❖ JSP pages require double the disk space to hold the JSP page.
❖ JSP pages require more time when accessed for the first time as they are to be

4. JSP Vs. Servlet


❖ A Servlet is a Java class implementing the javax.servlet.Servlet interface that runs within a
Web or application server’s Servlet engine, servicing client requests forwarded to it through
the server.
❖ A Java Server Page is a slightly more complicated.
❖ JSP pages contain a mixture of HTML , Java Scripts, JSP elements and JSP directives.
❖ The elements in a Java Server Page will generally be compiled by the JSP engine into a
Servlet, but the JSP specification only requires that the JSP page execution entity follow the
Servlet protocol.
❖ One advantage of JSP over Servlet is that the JSP allows a logical division between what is
displayed and the Web server side code specification that dictates what content fills the
page.
❖ It is easy to modify the look and feel of what is delivered by JSP without having to alter
any Web server side , Java code specification.
❖ Other advantage of JSP is that they are document – centric. On the other hand, Servlet look
and act like programs.
❖ A Java Server Page can contain Java program fragments that instantiate and execute Java
classes, but these occur inside an HTML template file and are primarily used to generate
dynamic content.
❖ Some of the JSP functionality can be achieved on the client using Javascript.
❖ While it’s true that anything done with a JSP can also be done with using a Servlet, JSPs
provides a nice clean separation of the application’s presentation layer from its data
manipulating layer.
❖ JSP is simple than Servlet. JSPs and Servlets work well together.

Shri M M Ghodasara Mahila College,Junagadh Page 2 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

❖ Thus, both Servlets and JSP pages have many features in common, and can be used for
developing dynamic Web contents.

5. JSP Architecture
❖ Typically, JSP pages are subject to a translation phase and a request phase.
❖ The translation phase is carried out only once, unless the JSP page changes.
❖ The communication of web browser and web server in terms of JSP is show in next figure.

❖ JSP are built by Sun Microsystems servlet technology .


❖ JSP tag contains Java code and its file extension is .jsp .the JSP engine parses the .jsp and
creates a java servlet source file.
❖ Then it compile the source file into a class file ,this is done first time only time.
❖ Step for JSP request which are as follows
▪ When the user goes to a JSP page web browser makes the request via internet.
▪ JSP request gets sent to the Web server.
▪ Web server recognize the .jsp file and passes the JSP file to the JSP Servlet Engine.
▪ If the JSP file has been called the first time the JSP file is parsed , otherwise servlet
is instantiated.
▪ The next step is to generate a special servlet file.the entire HTML statement
convert into println statement .
▪ The servlet source code is compile into a class.
▪ The servlet is instantiated , calling the init and service methods.
▪ HTML from the sevlet output is sent via the internet .
▪ HTML results are displayed on the user’s web browser.

Shri M M Ghodasara Mahila College,Junagadh Page 3 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

6. JSP life cycle


❖ JSP allow you to write standard HTML pages containing tags that run powerful programs
based on Java technology.
❖ The goal of JSP technology is to support separation of presentation and business logic.
❖ Web designer can design and update pages without learning the java technology.
❖ Similarly, java developer can write codes without dealing with web page design.
❖ The process of converting in to the servlet file is done in background by web container .

❖ Javax.servlet.jsp.HttpJspPage interface is used to create servlet from JSP file

❖ Previous figure shows the JSP life cycle. It shows that if the JSP page is requested first time
by web client to web container.
❖ Then requested JSP code is converted into servlet code into the translation phase.
❖ After that in complication phase converted servlet code is complied and byte code is
created in the from of servlet class.
❖ In next phase servlet class is loaded into servlet engine and servlet instance is created
❖ After creating instance it goes to the request process phase.
❖ The JSP pages follows these phases:
▪ Translation of JSP Page
▪ Compilation of JSP Page
▪ Class loading (class file is loaded)
▪ Instantiation (Object of the Generated Servlet is created).
▪ Initialization ( jspInit() method is invoked by the container).
▪ Reqeust processing ( _jspService() method is invoked by the container).
▪ Destroy ( jspDestroy() method is invoked by the container).
❖ Following in-built methods of Javax.servlet.jsp.HttpJspPage interface is called during the
JSP life cycle.

Shri M M Ghodasara Mahila College,Junagadh Page 4 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

▪ jspInit()
▪ When JSP servlet instance (object) is created jspInit() method will be called
▪ It is similar to init() method of servlet.
Syntax:
public void jspInit()
▪ _jspService()
▪ When JSP servlet instance (object) is called _jspService() method will be
called at the time request and response object (implicit obj) are sent.
▪ It is similar to service() method of servlet.
Syntax:
Public void_jspService(HttpServletRequest req,HttpServletResponse res)
throws ServletException ,IOException
▪ jspDestroy()
▪ When JSP servlet instance (object) is destroy _jspDestroy() method will be
called
▪ It is similar to jspDestroy() method of servlet.
Syntax:
Public void jspDestroy()

7. JSP Elements
❖ JSP elements are instruction to JSP container about what code to generate and how it
should operate.
❖ JSP elements have a special identity to JSP complier because it starts and ends with special
kind of tags.
❖ Template data (HTML code) is not complied by the jsp complier and also not recognize by
the JSP container .
❖ It is also known as Component of JSP page.
❖ JSP elements are as follows:
• Directive elements
• Scripting elements
• Action elements
(1) Directive elements
❖ The directives are messages that tells the web container how to translate a JSP page into
corresponding servlet.There are three types of directives:
• page directive
• include directive
• taglib directive
Syntax
▪ <%@ directive attribute=“value” %>
1.1 Page directive
❖ The page directive defines attributes that apply to an entire JSP page.
Syntax of JSP page directive
<%@ page [attribute1=“value” attribute2=“value”……..attributen=“valuen”] %>
◼ Following are the attributes…..
▪ import
▪ contentType

Shri M M Ghodasara Mahila College,Junagadh Page 5 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

▪ extends
▪ info
▪ buffer
▪ language
▪ isThreadSafe
▪ session
▪ pageEncoding
▪ errorPage
▪ isErrorPage

◼ Import
▪ The import attribute is used to import class, interface or all the members of a
package. It is similar to import keyword in java class or interface.
▪ Following packages are automatically imported with JSP page.
◼ Java.servlet.*
◼ java.servlet.http.*
◼ java.servlet.jsp.*
◼ Java.lang.*
▪ Example of import attribute
<%@ page import=“java.util.Date” %>
◼ contentType
▪ The contentType attribute defines the MIME(Multipurpose Internet Mail Extension)
type of the HTTP response.The default value is "text/html;charset=ISO-8859-1".
▪ Example of contentType attribute
<%@ page contentType=“text/html” charset=“UTF-8” %>
◼ extends
▪ The extends attribute defines the parent class that will be inherited by the generated
servlet.It is rarely used.
◼ info
▪ This attribute simply sets the information of the JSP page which is retrieved later by
using getServletInfo() method of Servlet interface.
Example of info attribute
<%@ page info=“Composed by abc” %>
▪ The web container will create a method getServletInfo() in the resulting servlet.For
example:
◼ buffer
▪ The buffer attribute sets the buffer size in kilobytes to handle output generated by
the JSP page. The default size of the buffer is 8Kb.
Example of buffer attribute
▪ <%@ page buffer=“16kb” %>
◼ language
▪ The language attribute specifies the scripting language used in the JSP page. The
default value is "java".
▪ Most probably its valid value is java only.
◼ isThreadSafe
▪ Servlet and JSP both are multithreaded. If you want to control this behavior of JSP
page, you can use isThreadSafe attribute of page directive. The value of
isThreadSafe value is true. If you make it false,

Shri M M Ghodasara Mahila College,Junagadh Page 6 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

▪ The web container will serialize the multiple requests, i.e. it will wait until the JSP
finishes responding to a
▪ request before passing another request to it. If you make the value of isThreadSafe
attribute like:
▪ <%@ page isThreadSafe="false" %>
◼ Session
▪ it defines the Boolean indicating value if the jsp page require HTTP session then its
value is true otherwise it become false.
▪ The default value is true.

◼ PageEncoding
▪ It define the character encoding of jsp page itself.
◼ errorPage
▪ 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.
◼ isErrorPage
▪ The isErrorPage attribute is used to declare that the current page is the error page.
Example

Syntax for all the page directive


<% @ page
[import=“java.util.*, java.sql.*” ]
[contentType=“text/html; charset=ISO-8859-1”]
[session=“true/false”]
[buffer=“size in kb”]
[autoFlush=“true/false”]
[info=“Some info message.”]
[errorPage=“error.jsp”]
[isErrorPage=“false/true”]
[isThreadSafe=“true/false”]
[language=“java”]
[extends=“package.class” ]
%>
1.2 Include directive
The include directive is used to include the contents of any resource it may be jsp file, html file
or text file.
❖ The include directive includes the original content of the included resource at page
translation time.
Shri M M Ghodasara Mahila College,Junagadh Page 7 of 36
J2EE 3. JSP,Java Beans B.C.A. SEM -5

❖ The code of the included file is added to the JSP document.


Syntax of include directive
<%@ include file=“filename” %>
 Example
◼ //header.jsp
<html><body>
<h1><%=new java.util.Date(); %></h1>
</body></html>
◼ //main.jsp
<%@ include file=“header.jsp” %>
<html><body>
The above content is included from header.jsp
</body></html>
1.3 Taglib directive
❖ The JSP taglib directive is used to define a tag library that defines many tags. We use the
TLD (Tag Library Descriptor) file to define the tags.
❖ In the custom tag section we will use this tag so it will be better to learn it in custom tag.
Syntax JSP Taglib directive
<%@ taglib url=“url of the tag library” prefix=“prefix of the tag library” %>

Example
<html>
<body>
<%@ taglib url=”http://www.javascript.com/tags “prefix=”mytag” %>
<mytag:currentdate>
</body>
</html>
</mytag:currentdate>

(2) Scripting elements


❖ The scripting elements provide the ability to insert java code inside the jsp. There are three
types of scripting elements:
• scriptlet tag
• expression tag
• declaration tag

2.1 scriptlet tag


❖ A scriptlet tag is used to execute java source code in JSP.
Syntax
<% java code %>
Example
<% out.wirte(“welcome to JSP”) %>
2.2 Expression tag
❖ The code placed within 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.
Syntax of JSP expression tag
<%= statement %>

Shri M M Ghodasara Mahila College,Junagadh Page 8 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

Example
<%= “welcome to JSP” %>
“Note that do not add the semicolon at the end of statement in the case of expression tag”
<%= new java.util.Date() %>
2.3 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. So it
doesn't get memory at each request.

Syntax of JSP declaration tag


<%! Statement %>
Example (that declare field)
<%! int data=10; %>
<%= “value of variable :”+data %>
Example (that declare method)
• In this example of JSP declaration tag, we are defining the method which returns the
cube of given number and calling this method from the jsp expression tag.
<html>
<body>
<%!
int cube(int n)
{
return (n*n*n);
}
%>
<%= “cube of 3:”+cube(3) %>
</body>
</html>
(3) Action elements
❖ Action element are high level jsp element which are used to create, modify and use other
objects
❖ Some standard action element in JSP page are as follows
• jsp:include
• jsp:forward
• jsp:param
• jsp:plugin
(3.1) jsp:include
❖ The jsp:include action tag is used to include the content of another resource it may be jsp,
html or servlet. The jsp include action tag includes the resource at request time
❖ so it is better for dynamic pages because there might be changes in future.
Syntax

<jsp:include page=“filename” flush=“true/false”>


[ <jsp:param name=“Paramname” value=“ParamValue” /> ]
</jsp:include>
Where,
Page:-Any JSP/HTML file which will be included
Flush:-it is an optional parameter used to flush buffer

Shri M M Ghodasara Mahila College,Junagadh Page 9 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

Example :jsp:include
printdate.jsp
<html><body>
<h1><%=new java.util.Date(); %></h1>
</body></html>
//main.jsp
<html><body>
<jsp:include page=“printdate.jsp”/>
<h1>End of main page</h1>
</body></html>
(3.2) jsp:forward
❖ The jsp:forward action tag is used to forward (transfer) control request to another resource
it may be jsp, html or another resource.
Syntax of jsp:forward
<jsp:forward page=“destinationpage”>
[ <jsp:param name=“Paramname” value=“ParamValue” /> ]
</jsp:forward>
Example
//printdate.jsp
<html><body>
<h1><%=new java.util.Date(); %></h1>
</body></html>
//main.jsp
<html><body>
<jsp:forward page=“printdate.jsp”/>
<h1>End of main page</h1></body</html>
(3.3) jsp:param
❖ This element is used to provide the tag/value pairs of information by including these as sub-
attribute of the <jsp:include> ,<jsp:forward> and the <jsp:pulgin> actions
Syntax
<jsp:param name=“pname” value=“pvalue”/>
or
<jsp:param name=“pname” value=“pvalue”>
</jsp:param>
Where,
Pname:-is a name of parameter name which is being referenced
pvalue-:-is the value of parameter
Example
<!-- main.jsp -->
<html>
<body>
<h1> Demo of Param tag</h1>
<jsp:forward page="demo.jsp" >
<jsp:param name="color" value="red" />
</jsp:forward>
</body>
</html>
<!-- Demo.jsp -->
<html>

Shri M M Ghodasara Mahila College,Junagadh Page 10 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

<body>
<%= "<b>Your given color is:"+request.getParameter("color") %>
</body>
</html>
(3.4) jsp:plugin
❖ This element is used to embed an applet and java beans with the jsp page .
❖ The tag automatically detects the browser type and insert the appropriate HTML tag either
<embed> or <object> in the output.
Syntax
<jsp:plugin type=“plugintype” code=“class filename” codebase=“url” >
</jsp:plugin>
Example
<html>
<head><title>Applet Pulgin Demo</title>
</head>
<body>
<jsp:plugin type="applet" code="Circle1.class" width="300" height="300">
</jsp:plugin>
</body>
</html>

Circle.java
import java.awt.*;
import java.applet.*;
/*<applet code=Circle1.class
height=500
width=500>
</applet>*/
public class Circle1 extends Applet
{
public void paint(Graphics g)
{
setBackground(Color.white);
Dimension d=getSize();
int x=d.width;
int y=d.height;
setForeground(Color.magenta);
g.fillOval(50,50,x-100,y-100);
}
}

8. Comments and template data


Comments
❖ We can use two types of comments with the JSP page one is for HTML and another for JSP
◼ HTML comments:- <!– this is HTML comment -->
◼ JSP Specific tag:-<%-- this is JSP comment --%>
- It will not appear in the page output to the client.
Template Data
❖ In JSP page , everything that is not a directive, declaration , scriplet, expression , action
element or JSP comment is termed as template data .

Shri M M Ghodasara Mahila College,Junagadh Page 11 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

❖ Usually , all the HTML and text in the page are called template data.
❖ Template data is ignore by JSP translator.
❖ This data is output to the client as if it had appeared within a static web page.

9. Implicit objects of JSP


❖ In servlet if we want to use the objects like request and response we need to explicitly
declare it within the servlet program.
❖ Like these some other objects which are frequently used with the JSP program are implicit
(hidden) within the JSP which are known as Implicit objects of JSP.
❖ Implicit objects means the objects which is already created by JSP itself.
❖ Implicit Objects are automatically created in JSP pages and can be used without declaring
their objects.
❖ Implicit Objects
• Request
• Response
• Out
• Session
• Config
• Exception
• Application
• Page

❖ Request Object
• This is most important objects which is used in JSP programming. The entire
request coming from the client can be obtained from this objects. Similar to servlet
programming request object in JSP also belongs to
javax.Servlet.http.HttpServletRequest Class.
• You can see all parameters which are sent by client through request object.
Methods
• Enumeration getParameterNames();
▪ Return the name of all Parameters.
• String getParameter(String name);
▪ Return the first value of a single request parameter.
• String getMethod();
▪ Return the Http Method for request weather it is GET or POST
• HttpSession getSession(), HttpSession getSession(boolean);
▪ Retrieves the session data for the request
• StringBuffer getRequestURL();
▪ Return the full URL of the request
Examples
login.jsp
<html>
<head>
<title>Request Object Demo</title>
</head>
<body>

Shri M M Ghodasara Mahila College,Junagadh Page 12 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

<h1>Request Object Demo</h1>


<form action="NextPage.jsp" method="get">
<table>
<tr>
<td>
Username &nbsp;&nbsp;&nbsp;
<input type="text" name="uname">
</td>
</tr>
<tr>
<td>
Password &nbsp;&nbsp;&nbsp;
<input type="password" name="password">
</td>
</tr>
<tr><td><br></td></tr>
<tr>
<td><input type="submit"></td>
</tr>
</table>
</form>
</body>
</html>

Nextpage.jsp
<html>
<head>
<title>Request Object Demo</title>
</head>
<body>
<h1>Request Object Demo</h1>

<%
String uname=request.getParameter("uname");
String password=request.getParameter("password");
String method=request.getMethod();
StringBuffer URL=request.getRequestURL();

%>

<h2>Username :- &nbsp;&nbsp; <%=uname %></h2>


<h2>Password :- &nbsp;&nbsp; <%=password %></h2>
<h2>Method you have used:- &nbsp;&nbsp; <%=method %></h2>
<h2>Full URL :- &nbsp;&nbsp; <%=URL %></h2>

</body>
</html>

Shri M M Ghodasara Mahila College,Junagadh Page 13 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

❖ Response Object
• This is another most important objects which is used in JSP programming. If you
want to generate any output for client, then you can generate it using response
object. As Similar to servlet programming response objects in JSP in belongs to
javax.servlet.http.HttpServletResponse class .
• The scope of the objects is page only because it is used to generate output of a
particular page.
Methods
▪ Enumeration getParameterNames();
• Return the name of all Parameters.

▪ Void setContentType(String Content Type);


• This method is used to set the content type e.g. setContentType(“text/html”);
▪ Void addCookie(Cookie cookie);
• Adding the specified cookie to the response.
▪ Void setHeader(String name,String value);
• Assign the specific value to the named header
▪ Void sendRedirect(String location)
• This method is used to redirect the page to the another location.

Example
login.jsp
as above code

successfully.jsp
<html>
<head>
<title>Response Object Demo</title>
</head>
<body>
<h1>Response Object Demo</h1>
<h2>Successfully Login</h2>

<%
String uname=request.getParameter("uname");
String password=request.getParameter("password");

if(! (uname.equals("Alish") && password.equals("alish123")) )


{
response.sendRedirect("Error.jsp");
}
%>

<h2> Helllo &nbsp;&nbsp; <%=uname %></h2>


<h2> Your Password is :- &nbsp;&nbsp; <%=password %></h2>

</body>
</html>

Shri M M Ghodasara Mahila College,Junagadh Page 14 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

error.jsp
<html>
<head>
<title>Response Object Demo</title>
</head>
<body>
<h1>Response Object Demo</h1>
<h2>Invalid Username or Password</h2>

<br><br>

<form action="Login.jsp" method="get">


<input type="submit" value="Back">
</form>
</body>
</html>

❖ Out Object
• This object is used to write output into the output stream of clients. The scope of out
is current page. Out object is created using javax.setrvlet.jsp.JspWriter class. There
are several methods under out implicit objects.
Methods
• Void print(), void println();
▪ This method is used to print the output on the page.
• Void clear()
▪ Clear the output buffer. If the buffer contents have already been transmitted
to the client, this method will cause an IOExceptionto be thrown.
• Void clearBuffer()
▪ Similar to clear(), but does not throw an exception if the buffer has already
been flushed.

❖ Session Object
• As the name suggest, this session implicit object is used for session tracking.
This belongs to javax.Servlet.http.HttpSession class. Session object for requesting
the client is created under session implicit object.
Methods
• Public Object getAttribute(String name)
▪ Returns the object bound with the specified name in this session, or null if
no object is bound under the name.
• public void setAttribute(String name, Object value)
▪ This method is used to set the attribute to the session
• public void removeAttribute(String name)
▪ This method is used to remove the attribute to the session
• public long getCreationTime()
▪ Returns the time when this session was created, measured in milliseconds

Shri M M Ghodasara Mahila College,Junagadh Page 15 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

Example
Firstpage.jsp
<html>
<body>
<%
session.setAttribute("username","ABC");
%>
<h1>Session Object Demo</h1>
<h2>First Page</h2>
<form action="NextPage.jsp" method="get">
<input type="submit" value="Next Page">
</form>

</body>
</html>

Nextpage.jsp
<html>
<body>
<h1>Session Object Demo</h1>
<h2>Next Page</h2>

<%
String uname=session.getAttribute("username").toString();
%>

<h2>Username :- &nbsp;&nbsp; <%=uname %></h2>


</body>
</html>
❖ Config Object
• This implicit object is similar to servletConfig object of Servlet. Config is created
using javax.servlet.ServletConfig class. This is mainly used to read some initial
parameters which are passed to particular page.
Methods
• Public String getInitParameter(String name)
• Returns a String containing the value of the named initialization parameter, or null
if the parameter does not exist.
• Public Enumeration getInitParameterNames()
▪ Returns the names of the servlet's initialization parameters as an
Enumeration of String objects, or an empty Enumeration if the servlet has no
initialization parameters
Example
<html>
<body>
<h1>Config Object Demo</h1>
<h2>First Page</h2>

<h3><%= config.getServletName() %></h3>


</body>

Shri M M Ghodasara Mahila College,Junagadh Page 16 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

</html>
❖ Exception Object
• This object is used to get the information about the exception (runtime errrors).
• This object is exists in java.lang.Throwable class.
Methods
• public String getMessage()
▪ Returns the detail message string of this throwable.
Example
Main.jsp
<%@ page errorPage="Error.jsp" %>
<html>
<body>
<h1>Exception Object</h1>
<%
int a=10;
int b=0;
b=a/b;
%>
<h2>Answer is &nbsp; <%=b %></h2>
</body>
</html>
Error.jsp
<%@ page isErrorPage="true" %>

<html>
<head>

</head>
<body>
<h3><%=exception.getMessage() %> exception has been occcured. </h3>
</body>
</html>

❖ Application Object
• This implicit object is used to set the values and attribute at application level.
Application object of JSP is similar to ServletContext object of Servlet
Programming.
Methods
• public Object getAttribute(String name)
▪ Return the attribute with the specified name
• public Enumeration getAttributeNames()
▪ Return the attribute with the names available within the application
• public void setAttribute(String name, Object object)
▪ Store the object with the given object name in the application
• public void removeAttribute(String name)
▪ Remove the name of the object mentioned in the parameter of this method
from the object of the application.

Shri M M Ghodasara Mahila College,Junagadh Page 17 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

Example
Firstpage.jsp
<html>
<body>

<h1>Application Object Demo</h1>


<h2>First Page</h2>
<%
application.setAttribute("username","ABC");
%>

<form action="NextPage.jsp" method="get">


<input type="submit" value="Next Page">
</form>
</body>
</html>

//nextpage.jsp
<html>
<body>
<h1>Application Object Demo</h1>
<h2>Next Page</h2>

<%
String uname=application.getAttribute("username").toString();
%>

<h2>Username :- &nbsp;&nbsp; <%=uname %></h2>


</body>
</html>
❖ Page Object
• JSP page is converted into Servlet Class at last. Then servlet instance is created of
that particular JSP servlet class.
• Page is the instance of JSP servlet class created by web container for the current
request.
• It contains the methods of object class along with all the methods created inside JSP
Page.
10. Scope of the JSP objects or JSP Scope
❖ Objects that are created as part of a JSP page have a certain lifetime and may or may not be
accessible to other components in the web application.
❖ The lifetime and accessibility of an object is known as scope.
❖ In some case, such as with the implicit objects (will discuss in next section), the scope is set
and can’t be changed. There are four valid scope
▪ Page scope
▪ Request scope
▪ Session scope
▪ Application scope

Shri M M Ghodasara Mahila College,Junagadh Page 18 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page scope
▪ This scope is the most restrictive. With page scope , the object is accessible only
within the current JSP page in which it is defined.
▪ JavaBeans created with page scope and object created by scriplets are thread-safe.
▪ JSP implicit objects out, exception , response , config , pageContext and page have
‘page’ scope
Request scope
▪ JSP object created using the request scope can be accessed from any pages that
serve that request.
▪ This means that the object is available within the page in which it is created , and
within the request is forwarded or included .
▪ Object with request scope are thread-safe. Only the execution thread for a particular
request can access these objects
▪ JSP implicit objects request have ‘request’ scope
Session scope
▪ JSP object created using the session scope are available to all application
components that participate in the client’s session these objects are not thread-safe.
▪ If the multiple requests could use the same session object at the same time, you
must synchronized access to that object .
▪ JSP implicit objects session have ‘session’ scope
Application scope
▪ This scope is the least restrictive.
▪ JSP object created using the application scope are available to entire application
for the life of the application.
▪ These objects are not thread-safe and access to them must be synchronized
▪ If the multiple requests could use the same application object at the same time
▪ JSP implicit objects application have ‘application’ scope

11. Including and Forwarding from JSP Page


❖ Include Action
• Including a JSP Page or Servlet through a standard action differs from the include
directive.
Syntax :-
<jsp:include file=“Path of File” flush=“true/false”>
[ <jsp:param name=“Paramname” value=“ParamValue” /> ]
</jsp:include>
❖ When the JSP container translate the page, this include directive causes the indicate file to
be included in that place in the page and become part of the java source file that is compiled
into the JSP Page implementation class; that is , it is included at translation time. Using the
include directive, included file does not need to be a complete and valid JSP Page.
❖ With the “include” standard action, the JSP file stops processing the current request and
passes the request to the included file. The included file passes its output to the response.
❖ After that control of the response returns to the calling JSP, which completes further
process of response. The output of included page or servlet is included at request time.
❖ Components that are include action must be valid JSP pages or servlet.
❖ The included file is neither allowed to modify the headers of response nor to set cookies in
the response.
❖ For the include element the page attribute is require and its value is the URL of the page
whose output is included in the response.
Shri M M Ghodasara Mahila College,Junagadh Page 19 of 36
J2EE 3. JSP,Java Beans B.C.A. SEM -5

❖ This URL is relative to the JSP page. The flush attribute is optional, and it indicates
weather the output buffer should be flushed before the included file is call. The default
value is false.
❖ If the JSP needs to pass parameters to the included file, it does so with the <jsp:param>
element.
❖ One element is used for each parameter. This element is optional.
• If it is included, both the name and value attribute are required.
• The included JSP Page can access the parameters using the getParamenter() and
getParameters method of request object.
Example
<html>
<body>
<form method="get">
<table cellspacing="0" cellpadding="0">
<tr>
<td>
<jsp:include page="header.jsp" flush="false">
<jsp:param name="test" value="JSP Demo"></jsp:param>
</jsp:include>
</td>
</tr>
<tr>
<td height="500px" width="1500" bgcolor="#22aaff" style="font-size:40px">
This is the content part of the page.
</td>
</tr>
</table> </form> </body> </html>
Header.jsp
<% String name = request.getParameter("test"); %>
<table>
<tr>
<td height="200px" width="1500" bgcolor="#ff22aa" style="font-size:40px">
This is the header part of page.
<br>
Name is <%=name%>
</td> </tr> </table>
Forward Action
❖ With the forward action , the current page stops processing the request and forwards the
request to another web components .
❖ This other components completes the response and execution never return to calling page.
Unlike the include action , which can occur at any time during a response .
❖ The forward action must occur prior to writing any output to the OutputStream.
Syntax :-
<jsp:forward page=“URL” >
[ <jsp:param name=“Paramname” value=“ParamValue” /> ]
</jsp:forward>
❖ The meaning and use of attributes and of the <jsp:param> element are the same as those for
include the action.

Shri M M Ghodasara Mahila College,Junagadh Page 20 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

Example
<html>
<body>
<h1>Forward Action Demo</h1>
<%
String uname = "mmg";
if (uname.equals("mmg")) {
%>
<jsp:forward page="NextPage.jsp" >
<jsp:param name="uname" value="<%=uname%>"></jsp:param>
</jsp:forward>
<% } %>
<h2>Invalid username <%=uname%></h2>
</body>
</html>
Nextpage.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Forward Action Demo</title>
</head>
<body>
<% String uname= request.getParameter("uname"); %>
<h1>Forward Action Demo</h1>

<h2>Username is &nbsp;&nbsp;<%=uname %></h2>


</body>
</html>
12. Working with Session and Cookie in JSP
Cookie

Cookies are text files stored on the client computer and they are kept for various information
tracking purpose. JSP transparently supports HTTP cookies using underlying servlet
technology.

There are three steps involved in identifying returning users:

• Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
• Browser stores this information on local machine for future use.
• When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user or may be
for some other purpose as well.

Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly
on a browser). A JSP that sets a cookie might send headers that look something like this:

HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;

Shri M M Ghodasara Mahila College,Junagadh Page 21 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html

As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a
domain. The name and value will be URL encoded. The expires field is an instruction to the
browser to "forget" the cookie after the given time and date.

If the browser is configured to store cookies, it will then keep this information until the expiry
date. If the user points the browser at any page that matches the path and domain of the cookie,
it will resend the cookie to the server. The browser's headers might look something like this:

GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)

Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz

A JSP script will then have access to the cookies through the request method
request.getCookies() which returns an array of Cookie objects.

Servlet Cookies Methods:

Following is the list of useful methods associated with Cookie object which you can use while
manipulating cookies in JSP:

S.N. Method & Description


public void setDomain(String pattern)
1
This method sets the domain to which cookie applies, for example tutorialspoint.com.
public String getDomain()
2
This method gets the domain to which cookie applies, for example tutorialspoint.com.
public void setMaxAge(int expiry)
3 This 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.
public int getMaxAge()
4 This method returns the maximum age of the cookie, specified in seconds, By default, -1
indicating the cookie will persist until browser shutdown.
public String getName()
5
This method returns the name of the cookie. The name cannot be changed after creation.
public void setValue(String newValue)
6
This method sets the value associated with the cookie.
public String getValue()
7
This method gets the value associated with the cookie.
public void setPath(String uri)
8 This method sets the path to which this cookie applies. If you don't specify a path, the
cookie is returned for all URLs in the same directory as the current page as well as all

Shri M M Ghodasara Mahila College,Junagadh Page 22 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

subdirectories.
public String getPath()
9
This method gets the path to which this cookie applies.
public void setSecure(boolean flag)
10 This method sets the boolean value indicating whether the cookie should only be sent over
encrypted (i.e. SSL) connections.
public void setComment(String purpose)
11 This method specifies a comment that describes a cookie's purpose. The comment is
useful if the browser presents the cookie to the user.
public String getComment()
12 This method returns the comment describing the purpose of this cookie, or null if the
cookie has no comment.

Setting Cookies with JSP:

Setting cookies with JSP involves three steps:

(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");

Keep in mind, neither the name nor the value should contain white space or any of the
following characters:

[ ] ( ) = , " / ? @ : ;

(2) Setting the maximum age: You use setMaxAge to specify how long (in seconds) the
cookie should be valid. Following would set up a cookie for 24 hours.

cookie.setMaxAge(60*60*24);

(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);

Example:
<%
// 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);

Shri M M Ghodasara Mahila College,Junagadh Page 23 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

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

Let us put above code in main.jsp file and use it in the following HTML page:

<html>
<body>
<form action="main.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>

Keep above HTML content in a file hello.jsp and put hello.jsp and main.jsp in <Tomcat-
installation-directory>/webapps/ROOT directory. When you would access
http://localhost:8080/hello.jsp, here is the actual output of the above form.

First Name:
Last Name:

Try to enter First Name and Last Name and then click submit button. This would display first
name and last name on your screen and same time it would set two cookies firstName and
lastName which would be passed back to the server when next time you would press Submit
button.

Next section would explain you how you would access these cookies back in your web
application.

Reading Cookies with JSP:

To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the
getCookies( ) method of HttpServletRequest. Then cycle through the array, and use getName()
and getValue() methods to access each cookie and associated value.
Shri M M Ghodasara Mahila College,Junagadh Page 24 of 36
J2EE 3. JSP,Java Beans B.C.A. SEM -5

Example:

Let us read cookies which we have set in previous example:

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

Now let us put above code in main.jsp file and try to access it. If you would have set first_name
cookie as "Dhara" and last_name cookie as "Patel" then running http://localhost:8080/main.jsp
would display the following result:

Found Cookies Name and Value

Name : first_name, Value: Dhara


Name : last_name, Value: Patel

Delete Cookies with JSP:

To delete cookies is very simple. If you want to delete a cookie then you simply need to follow
up following three steps:

• Read an already existing cookie and store it in Cookie object.


• Set cookie age as zero using setMaxAge() method to delete an existing cookie.
• Add this cookie back into response header.

Example:

Following example would delete an existing cookie named "first_name" and when you would
run main.jsp JSP next time it would return null value for first_name.

Shri M M Ghodasara Mahila College,Junagadh Page 25 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

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

Now let us put above code in main.jsp file and try to access it. It would display the following
result:

Cookies Name and Value

Deleted cookie : first_name


Name : first_name, Value: Dhara
Name : last_name, Value: Patel

Now try to run http://localhost:8080/main.jsp once again and it should display only one cookie
as follows:

Found Cookies Name and Value

Name : last_name, Value: Patel

You can delete your cookies in Internet Explorer manually. Start at the Tools menu and select
Internet Options. To delete all cookies, press Delete Cookies.

Shri M M Ghodasara Mahila College,Junagadh Page 26 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

JSP - Session Tracking


HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the client
opens a separate connection to the Web server and the server automatically does not keep any
record of previous client request.

Still there are following three ways to maintain session between web client and web server:

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 because many time browser does not support a cookie, so I
would not recommend 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 POST data. Each time when web browser sends request
back, then session_id value can be used to keep the track of different web browsers.

This could 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 on the end of each URL that identifies the session, and the
server can associate that session identifier with 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 but here drawback is that you would have generate every URL dynamically to
assign a session ID though page is simple static HTML page.

The session Object:

Apart from the above mentioned three ways, JSP makes use of servlet provided HttpSession
Interface which provides a way to identify a user across more than one page request or visit to a
Web site and to store information about that user.

Shri M M Ghodasara Mahila College,Junagadh Page 27 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

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

The JSP engine exposes the HttpSession object to the JSP author through the implicit session
object. Since session object is already provided to the JSP programmer, the programmer can
immediately begin storing and retrieving data from the object without any initialization or
getSession().

Here is a summary of important methods available through session object:

S.N. Method & Description


public Object getAttribute(String name)
1 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()
2 This method returns an Enumeration of String objects containing the names of all the
objects bound to this session.
public long getCreationTime()
3 This method returns the time when this session was created, measured in milliseconds
since midnight January 1, 1970 GMT.
public String getId()
4
This method returns a string containing the unique identifier assigned to this session.
public long getLastAccessedTime()
5 This method returns the last time the client sent a request associated with this session, as
the number of milliseconds since midnight January 1, 1970 GMT.
public int getMaxInactiveInterval()
6 This method returns the maximum time interval, in seconds, that the servlet container will
keep this session open between client accesses.
public void invalidate()
7
This method invalidates this session and unbinds any objects bound to it.
public boolean isNew(
8 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)
9
This method removes the object bound with the specified name from this session.
public void setAttribute(String name, Object value)
10
This method binds an object to this session, using the name specified.
public void setMaxInactiveInterval(int interval)
11 This method specifies the time, in seconds, between client requests before the servlet
container will invalidate this session.

Shri M M Ghodasara Mahila College,Junagadh Page 28 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

Session Tracking Example:

This example describes how to use the HttpSession object to find out the creation time and the
last-accessed time for a session. We would associate a new session with the request if one does
not already exist.

<%@ 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("ABCD");

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


if (session.isNew()){
title = "Welcome to my website";
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>
<center>
<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>

Shri M M Ghodasara Mahila College,Junagadh Page 29 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

<td>Number of visits</td>
<td><% out.print(visitCount); %></td>
</tr>
</table>
</body>
</html>

Now put above code in main.jsp and try to access http://localhost:8080/main.jsp. It would
display the following result when you would run for the first time:

Welcome to my website

Session Infomation

Session info value


Id 0AE3EC93FF44E3C525B4351B77ABB2D5
Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010
Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010
User ID ABCD
Number of visits 0

Now try to run the same JSP for second time, it would display following result.

Welcome Back to my website

Session Infomation

info type value


Id 0AE3EC93FF44E3C525B4351B77ABB2D5
Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010
Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010
User ID ABCD
Number of visits 1

Deleting Session Data:

When you are done with a user's session data, you have several options:

• Remove a particular attribute: You can call public void removeAttribute(String


name) method to delete the value associated with a particular key.
• Delete the whole session: You can call public void invalidate() method to discard an
entire session.

Shri M M Ghodasara Mahila College,Junagadh Page 30 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

• Setting Session timeout: You can call 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 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.

13. Handling Errors and Exceptions


❖ Dealing with Exception in the page directive
❖ Dealing with exception in the Deployment Descriptor
❖ Adding Exception Handling in JSP pages
Dealing with exception in the page directive
❖ This is the first way to handle exception by creating an error page. To create an error page
with JSP we can use isErrorPage=true attribute of page directive.
❖ After creating an error page we can handle the exception with any JSP page by invoking
this error page with it using errorPage=“URL of the error page” attribute of the page
directive.
Example
Index.jsp
<html>
<body>
<form action="NextPage.jsp" method="get">
<table>
<tr>
<td>
Number 1 &nbsp;&nbsp;
<input type="text" name="num1">
</td>
</tr>
<tr>
<td>
Number 2 &nbsp;&nbsp;

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


</td>
</tr>
<tr><td><br></td></tr>
<tr>
<td>
Shri M M Ghodasara Mahila College,Junagadh Page 31 of 36
J2EE 3. JSP,Java Beans B.C.A. SEM -5

<input type="submit" value="Answer">


</td>
</tr>
</table>
</form>
</body>
</html>
Nextpage.jsp
<%@ page errorPage="Error.jsp" %>
<html>
<body>
<%
int a=0;
int num1=Integer.parseInt(request.getParameter("num1"));
int num2=Integer.parseInt(request.getParameter("num2"));
a=num1/num2;
%>

<h2> Division is &nbsp; <%=a %></h2>


<a href="index.jsp">Back</a>
</body>
</html>

Error.jsp
<%@ page isErrorPage="true" %>
<html>
<body>
<h2><%= exception.getMessage() %></h2>
</body>
</html>
Dealing with exception in the deployment descriptor
❖ This is the second way by which we can handle an exception with the JSP Page.
Deployment Descriptor is a web.xml file which defines the classes, resources and
configuration of the application and how the server uses them to serve web requests.
❖ It resides in the application under the WEB-INF/ directory.
❖ If an error page is define for handling an exception, the requests is directed to the error
page’s URL.
❖ The web application deployment descriptor uses the <error-page> tag to define web
components that handle errors.
❖ We can set deployment descriptor for error handling in two ways, either using exception
type or using error code.
Exception type
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>Error.jsp</location>
</error-page>
Error code
<error-page>

Shri M M Ghodasara Mahila College,Junagadh Page 32 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

<error-code>500<error-code>
<location>Error.jsp</location>
</error-page>
Example:
Index.jsp
<html>
<body>
<%
int a=10,b;
b=a/0;
%>
<h2>Answer is &nbsp; <%=b %></h2>
</body>
</html>
Error.jsp //Same as above code
Web.xml
<web-app>
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/Error.jsp</location>
</error-page>
</web-app>

Adding Exception Handling in JSP page


❖ Exception can be handle in a scriptlet in the same way as in java, by using the try-catch
block.
Example
<html>
<body>
<% int a;
try
{ a=10/0;
out.println("Division is " + String.valueOf(a));
}
catch(Exception e)
{ out.println(e.getMessage());
}
%>
</body>
</html>

14. JDBC With JSP


Connectivity of JSP with JDBC
Access Database Connectivity Steps:

A PDF’S 35 PROGRAM

Shri M M Ghodasara Mahila College,Junagadh Page 33 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

1. JavaBean Properties
• A JavaBean is a specially constructed Java class written in the Java and coded according
to the JavaBeans API specifications.
• A JavaBean is a reusable software component that can be manipulated visually in an
application builder tool.
• Following are the unique characteristics that distinguish a JavaBean from other Java
classes:

• It provides a default, no-argument constructor.


• It should be serializable and implement the Serializable interface.
• It may have a number of properties which can be read or written.
• It may have a number of "getter" and "setter" methods for the properties.

2. Advantages of JavaBeans
• It provides the property of “write once and run anywhere”.
• It can work in different local machines.
• Beans have the capability of capturing the events sent by other objects .
• The properties, events and methods of the bean can be controlled by the application
developer.
• Configuration setting of a bean can be saved in persistent storage.

3. Properties of JavaBeans
• A JavaBean property is a named attribute that can be accessed by the user of the object.
• The attribute can be of any Java data type, including classes that you define.
• A JavaBean property may be read, write, read only, or write only.
• Indexed Properties:- An indexed property is an array instead of a single value. In this
case, the bean class provides a method for getting and setting the entire array
• Bound Properties:- A bound property notifies listeners when its value changes. This has
two implications:
▪ The bean class includes addPropertyChangeListener() and
removePropertyChangeListener() methods for managing the bean's listeners.
▪ When a bound property is changed, the bean sends a PropertyChangeEvent to its
registered listeners.
• The javabean property is like tag’s name and value
• JavaBean properties are accessed through two methods in the JavaBean's implementation
class:
Method Description
For example, if property name is firstName, your method name
getPropertyName() would be getFirstName() to read that property. This method is
called accessor.
For example, if property name is firstName, your method name
setPropertyName() would be setFirstName() to write that property. This method is
called mutator.

A read-only attribute will have only a getPropertyName() method, and a write-only attribute
will have only a setPropertyName() method.

4. JavaBean Method

Shri M M Ghodasara Mahila College,Junagadh Page 34 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

• The Beans class is never meant to be instantiated; its static methods provide
miscellaneous JavaBeans features.

1) The instantiate() method creates an instance of a bean. The specified bean name
represents either a serialized bean file or a bean class file; it is interpreted relative to the
specified ClassLoader object.

2) The setDesignTime() and isDesignTime() methods are used to set and query a flag that
indicates whether beans are being used in an application builder environment.

3) setGuiAvailable() and isGuiAvailable() set and query a flag that indicates whether the
Java Virtual Machine is running in an environment in which a GUI is available.

4) isInstanceOf() method is a replacement for the Java instanceof operator for use with
beans. Currently, it behaves just like instanceof, but in the future it may work with beans that
consist of a set of Java objects, each of which provides a different "view" of a bean.

5) getInstanceOf() method is a replacement for the Java cast operator. It converts a bean to a
superclass or interface type. Currently, it behaves just like a cast, but you should use it for
future compatibility with multiclass beans.

Common JavaBean Packaging


• Java bean are packaged and delivered in JAR files supported since JDK 1.1 JAR files are
used to collect class files, serialized objects, images, help files and similar resources files.
• A JAR file is a ZIP format archive file that may optionally have a manifest file.
• A manifest file contains additional information describing the contents of JAR files.
• A single JAR file may contain more than one java bean.
• The following is the basic example of a java bean class illustrates the common javabean
packaging mechanism.
1)Writing a first bean
• Create a simple bean
• Compiling and saving the bean into JAR file.
• Loading the bean into the GUI builder of the netbeans IDE.
FirstBean.java
Import java.awt.*;
Import java.io.Serializable;
Public class FirstBean extends Canvas
{
Public FirstBean()
{
setSize(60,40);
setBackground(Color.red);
}
}
This code set the size and background of canvas.
Make sure that the CLASSPATH environment variable is set to point to all needed .class file.
Compile the bean file
Javac FirstBean.java
Create a manifest file

Shri M M Ghodasara Mahila College,Junagadh Page 35 of 36


J2EE 3. JSP,Java Beans B.C.A. SEM -5

Manifest.tmp
Name:FirstBean.class
Java-Bean:True

Create the jar file which contain the manifest file and FirstBean class file.

Shri M M Ghodasara Mahila College,Junagadh Page 36 of 36

You might also like