ch3
ch3
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.
▪
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
❖ 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.
❖ 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.
▪ 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
▪ 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,
▪ 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
Example
<html>
<body>
<%@ taglib url=”http://www.javascript.com/tags “prefix=”mytag” %>
<mytag:currentdate>
</body>
</html>
</mytag:currentdate>
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.
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>
<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);
}
}
❖ 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.
❖ 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>
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();
%>
</body>
</html>
❖ 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.
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");
</body>
</html>
error.jsp
<html>
<head>
<title>Response Object Demo</title>
</head>
<body>
<h1>Response Object Demo</h1>
<h2>Invalid Username or Password</h2>
<br><br>
❖ 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
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();
%>
</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 <%=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.
Example
Firstpage.jsp
<html>
<body>
//nextpage.jsp
<html>
<body>
<h1>Application Object Demo</h1>
<h2>Next Page</h2>
<%
String uname=application.getAttribute("username").toString();
%>
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
❖ 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.
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>
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.
• 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;
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.
Following is the list of useful methods associated with Cookie object which you can use while
manipulating cookies in JSP:
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.
(1) Creating a Cookie object: You call the Cookie constructor with a cookie name and a
cookie value, both of which are strings.
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"));
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.
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:
<html>
<head>
<title>Reading Cookies</title>
</head>
<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookie cookie = null;
Cookie[] cookies = null;
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:
To delete cookies is very simple. If you want to delete a cookie then you simply need to follow
up following three steps:
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.
<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:
Now try to run http://localhost:8080/main.jsp once again and it should display only one cookie
as follows:
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.
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.
A web server can send a hidden HTML form field along with a unique session ID as follows:
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.
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.
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.
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:
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().
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.
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>
<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
Now try to run the same JSP for second time, it would display following result.
Session Infomation
When you are done with a user's session data, you have several options:
• 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.
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>
<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 <%=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>
A PDF’S 35 PROGRAM
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:
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
• 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.
Manifest.tmp
Name:FirstBean.class
Java-Bean:True
Create the jar file which contain the manifest file and FirstBean class file.