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

Bca It Chap3

The document discusses JSP (JavaServer Pages) and Java Beans. It provides an introduction to JSP, noting that it is a Java technology that enables the creation of dynamic web pages through special JSP tags. It also discusses using JSP to access databases via JDBC and to fulfill the role of a user interface for Java web applications. The document then provides examples of using JSP tags to output text, access JavaBeans components, and pass information between requests and pages.

Uploaded by

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

Bca It Chap3

The document discusses JSP (JavaServer Pages) and Java Beans. It provides an introduction to JSP, noting that it is a Java technology that enables the creation of dynamic web pages through special JSP tags. It also discusses using JSP to access databases via JDBC and to fulfill the role of a user interface for Java web applications. The document then provides examples of using JSP tags to output text, access JavaBeans components, and pass information between requests and pages.

Uploaded by

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

J2EE

Chapter - 3 : JSP And Java Beans


*JSP
JSP Introduction:


 -side programming technology that enables the
creation of dynamic, platform-independent method for building
Web-based applications.

JDBC API to access enterprise databases.

Webpages that supports dynamic content.
 ages by
making use of special JSP tags, most of which start with <% and
end with %>.

designed to fulfill the role of a user interface for a Java web
application.
 as text files that combine HTML or
XHTML code, XML elements, and embedded JSP actions and
commands.

forms, present records from a database or another source, and
create Webpages dynamically.

information from a database or registering user preferences,
accessing JavaBeans components, passing control between pages,
and sharing information between requests, pages etc.

Q.1 Difference between servlet and jsp

1
J2EE
SERVLET JSP

Servlet is a java code. JSP is a html based code.

Writing code for servlet is harder than JSP JSP is easy to code as it is java in html.

as it is html in java.

Servlet plays a controller role in MVC JSP is the view in MVC approach for

approach. showing output.

Servlet is faster than JSP. JSP is slower than Servlet because the

first step in JSP lifecycle is the

translation of JSP to java code and

then compile.

Servlet can accept all protocol requests. JSP only accept http requests.

In Servlet, we can override the service() In JSP, we cannot override its service()

method. method.

In Servlet by default session management is In JSP session management is

not enabled, user have to enable it explicitly. automatically enabled.

In Servlet we have to implement everything In JSP business logic is separated from

like business logic and presentation logic in presentation logic by using javaBeans.

just one servlet file.

Modification in Servlet is a time consuming JSP modification is fast, just need to

2
J2EE
task because it includes reloading, click the refresh button.

recompiling and restarting the server.

* A Simple Web Application


Example :
<html>
<title> a simple jsp file </title>
<body>
<h1>
<% out.println("hello world");%>
</h1>
</body>
</html>

Q.3 Discuss JSP architecture

JSP Processing
3
J2EE

web server.

and forwards it to a JSP engine.

servlet content.

forwards the original request to a servlet engine.

class and executes it.

of static HTML content.


-generated HTML
page inside the HTTP response exactly as if it were a static page.

Q.4 explain JSP LIFE CYCLE :

or a JSP resource, the engine receives


that request, and hands it over to the JSP along with a response object.
ct
to include all the other information that has to be sent to the client.
The engine then collects this information and passes it to the client.

javax.servlet.ServletRequest and javax.servlet.servleResponse or


Httpservletrequest and HttpServletResponse for the HTTP protocol
respectively.
jsp Page interface are given
below :

4
J2EE

Q.5 Explain JSP elements


There are three types of elements
A) Directives Elements (page, include, taglib)
B) Scripting Elements (Declaration, scriptlet, expression)
C) Action Elements (JSP:param, JSP:include, JSP:Forward, JSP:plugin)
A) Directives Elements (page, include, taglib)
The jsp directives are messages that tells the web container how to
translate a JSP page into the corresponding servlet.
There are three types of directives:
1.page directive
2.include directive
3.taglib directive

5
J2EE
 Syntax of JSP Directive
<%@ directive attribute="value" %>
1. JSP page directive
The page directive defines attributes that apply to an entire JSP page.
Syntax of JSP page directive
<%@ page attribute="value" %>
Attributes of JSP page directive
 import
 contentType
 extends
 info
 buffer
 language
 isELIgnored
 isThreadSafe
 autoFlush
 session
 pageEncoding
 errorPage
 isErrorPage
1)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.

Example of import attribute


<html>

6
J2EE
<body>
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>
</body>
</html>

2)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
<html>
<body>
<%@ page contentType=application/msword %>
Today is: <%= new java.util.Date() %>
</body>
</html>

3)extends
The extends attribute defines the parent class that will be inherited by
the generated servlet.It is rarely used.

4)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
7
J2EE
<html>
<body>
<%@ page info="created by computer student " %>
Today is: <%= new java.util.Date() %>
</body>
</html>
5)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


<html>
<body>
<%@ page buffer="16kb" %>
Today is: <%= new java.util.Date() %>
</body>
</html>

6)language
The language attribute specifies the scripting language used in the JSP
page. The default value is "java".

7)isELIgnored
We can ignore the Expression Language (EL) in jsp by the isELIgnored
attribute. By default its value is false i.e. Expression Language is
enabled by default. We see Expression Language later.

<%@ page isELIgnored="true" %>//Now EL will be ignored

8)isThreadSafe

8
J2EE
Servlet and JSP both are multithreaded.If you want to control this
behaviour 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,

9)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.
Example of errorPage attribute
//index.jsp
<html>
<body>
<%@ page errorPage="myerrorpage.jsp" %>
<%= 100/0 %>
</body>
</html>

10)isErrorPage
The isErrorPage attribute is used to declare that the current page is the
error page.

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 (the jsp page is translated only
once so it will be better to include static resource).
Advantage of Include directive
Code Reusability

9
J2EE
Syntax of include directive
<%@ include file="resourceName" %>

Example of include directive


In this example, we are including the content of the header.html file. To
run this example you must create an header.html file.
<html>
<body>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
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 uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>

Example of JSP Taglib directive


In this example, we are using our tag named currentDate. To use this tag
we must specify the taglib directive so the container may get information
about the tag.
<html>
<body>
<%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
<mytag:currentDate/>
10
J2EE
</body> </html>
B) Scripting Elements (Declaration, scriptlet, expression)
In JSP, java code can be written inside the jsp page using the scriptlet tag.
Let's see what are the scripting elements first.

The scripting elements provides the ability to insert java code inside the jsp.
There are three types of scripting elements:

o scriptlet tag
o expression tag
o declaration tag

1.scriptlet tag
A scriptlet tag is used to execute java source code in JSP. Syntax is as
follows:
<% java source code %>
Example of JSP scriptlet tag
In this example, we are displaying a welcome message.
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>

Example of JSP scriptlet tag that prints the user name


In this example, we have created two files index.html and welcome.jsp.
The index.html file gets the username from the user and the welcome.jsp
file prints the username with the welcome message.
File1: index.html
<html>
<body>
<form action="welcome.jsp">

11
J2EE
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form> </body> </html>
File2: welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</form> </body> </html>
2.expression tag

The code placed within JSP 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 %>

Example of JSP expression tag that prints the user name


In this example, we are printing the username using the expression tag.
The index.html file gets the username and sends the request to the
welcome.jsp file, which displays the username.

File1: index.jsp
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form> </body> </html>
12
J2EE
File2: welcome.jsp
<html>
<body>
<%= "Welcome "+request.getParameter("uname") %>
</body> </html>

2.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
<%! field or method declaration %>

Example of JSP declaration tag that declares field


In this example of JSP declaration tag, we are declaring the field and
printing the value of the declared field using the jsp expression tag.
index.jsp
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body> </html>

Difference between JSP Scriptlet tag and Declaration


tag
Jsp Scriptlet Tag Jsp Declaration Tag

The jsp scriptlet tag can only declare The jsp declaration tag can declare variables

13
J2EE
variables not methods. as well as methods.

The declaration of scriptlet tag is placed The declaration of jsp declaration tag is
inside the _jspService() method. placed outside the _jspService() method.

C) Action Elements (JSP:param, JSP:include, JSP:Forward, JSP:plugin)

 There are many JSP action tags or elements. Each JSP action tag is
used to perform some specific tasks.
 The action tags are used to control the flow between pages and to
use Java Bean. The Jsp action tags are given below.
 A JSP action directive provides an easy method to encapsulate the
 common tasks.
 These typically create or act on objects, usually JavaBeans.
 JavaBeans are components that are created once, and can be reused
over and over again.

1.JSP:Include:

JSP page.

Servlet.

we are including.
ollowing Example We Used 2 JSP Files, one.jsp file is sample file
which is included in second.jsp file.
Example:
First.JSP:
<html>
<head>
<title>JSP Include Example</title>
</head>
14
J2EE
<body>
<h1>This is the first.jsp File.</h1>
<jsp:include page="second..jsp" />
</body> </html>
Second.JSP:
<html>
<head>
<title>Second JSP File</title>
</head>
<body>
<h1>This is the second.jsp File. This File Included Using JSP Include
Action Tag.</h1>
</body> </html>

2.JSP:Forward:

resource (It can be a JSP, static page such as html or Servlet).


ded with or without parameter.
Example:
First.JSP
<html>
<head>
<title>JSP forward action tag example</title>
</head>
<body>
<p align="center">My main JSP page</p>
<jsp:forward page="display.jsp" />
</body>
</html>
Second.JSP

15
J2EE
<html>
<head>
<title>Display Page</title>
</head>
<body>
Hello this is a display.jsp Page
</body>
</html>

3.Jsp:Param
The <c:param> tag allows proper URL request parameter to be specified with
URL and also does the necessary URL encoding required.
Within a <c:param> tag, the name attribute indicates the parameter name, and the
value attribute indicates the parameter value −
Attribute
The <c:param> tag has the following attributes −

Attribute Description Required Default

name Name of the request parameter to set in the URL Yes None

value Value of the request parameter to set in the URL No Body

Example
If you need to pass parameters to a <c:import> tag, use the <c:url> tag to create
the URL first as shown below −
<c:url value = "/index.jsp" var = "myURL">
<c:param name = "trackingId" value = "1234"/>
<c:param name = "reportType" value = "summary"/>
</c:url>
<c:import url = "${myURL}"/>

16
J2EE
The above request will pass the URL as below - Try it yourself.
"/index.jsp?trackingId=1234;reportType=summary"

4.Jsp:Plugin

The jsp:plugin action tag is used to embed applet in the jsp file. The
jsp:plugin action tag downloads plugin at client side to execute an applet
or bean.
Syntax of jsp:plugin action tag
<jsp:plugin type= "applet | bean" code= "nameOfClassFile"
codebase= "directoryNameOfClassFile" >
</jsp:plugin>

Q.6 Explain about implicit objects


the examples discussed to far are those that work independently of
the HTTP request.
through HTTP protocols, JSP
has provided certain implicit objects.
t the request from the
browser, send the response from the server and also determine how
session tracking can be done.

1. Request :
 This is an object of HTTPServletRequest.
 This allows the developer to access the request parameters using
 getParameter(), the request type (GET, POST HEAD etc).
And the incoming HTTP header.
 However, if HTTP is not used, than request is usually an object of
javax.servlet.ServletRequest.
2.Response :
 This is an HttServletResponse object associated with the response
of the client.

17
J2EE
 This allows the developer to set the content type, which is to be
sent to the client's browser using the setContentType() method.
3.Out :
 This is an object of type javax.servlet,.jsp.Jsp writer.
 It is used for writing data to the output buffer.
 The buffer size can be adjusted or may even be turned off.
 You may recall that this can be done using the buffer attribute of
the page directive.
 The out object is used almost exclusively in scriptlets, as JSP
expressions get automatically placed in the output stream.
4.Session :
 This is HttpSession object associated with the request.
 The sessions are created automatically, so this variable is bound to
the page even if there is no incoming session reference.
However, there is one exception.
 The session attribute for a particular page may be sent to false.
 In this case, any attempt made to reference the session variable will
produce error.
5. Application :
 This a javax.servlet.ServletContext object.
 It is used to share information among all users of a currently active
application.
6. Confg :
 This object stores servlet configuration data, but rarely used.
 This is the javax.servlet.ServletConfig object.

Q.7 Explain cookies in jsp


A cookie is a small piece of information that is persisted between the
multiple client requests.

A cookie has a name, a single value, and optional attributes such as a


comment, path and domain qualifiers, a maximum age, and a version
number.

18
J2EE
How Cookie works

By default, each request is considered as a new request. In cookies


technique, we add cookie with response from the servlet. So cookie is
stored in the cache of the browser. After that if request is sent by the
user, cookie is added with request by default. Thus, we recognize the
user as the old user.

Types of Cookie

There are 2 types of cookies in servlets.

1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie

It is valid for single session only. It is removed each time when user
closes the browser.

Persistent cookie

It is valid for multiple session . It is not removed each time when user
closes the browser. It is removed only if user logout or signout.

Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.

Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.

Cookie class
javax.servlet.http.Cookie class provides the functionality of using
cookies. It provides a lot of useful methods for cookies.
19
J2EE
Constructor of Cookie class
Constructor Description

Cookie() constructs a cookie.

Cookie(String name, String constructs a cookie with a specified


value) name and value.

Useful Methods of Cookie class

There are given some commonly used methods of the Cookie class.

Method Description

public void Sets the maximum age of the cookie in


setMaxAge(int expiry) seconds.

public String getName() Returns the name of the cookie. The name
cannot be changed after creation.

public String getValue() Returns the value of the cookie.

public void changes the name of the cookie.


setName(String name)

public void changes the value of the cookie.


setValue(String value)

Other methods required for using Cookies


For adding cookie or getting the value from the cookie, we need some
20
J2EE
methods provided by other interfaces. They are:
1. public void addCookie(Cookie ck):method of
HttpServletResponse interface is used to add cookie in response
object.
2. public Cookie[] getCookies():method of HttpServletRequest
interface is used to return all the cookies from the browser.

How to create Cookie?

Let's see the simple code to create cookie.

1. Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object

2. response.addCookie(ck);//adding cookie in the response

How to delete Cookie?

Let's see the simple code to delete cookie. It is mainly used to logout or
signout the user.

1. Cookie ck=new Cookie("user","");//deleting value of cookie


2. ck.setMaxAge(0);//changing the maximum age to 0 seconds
3. response.addCookie(ck);//adding cookie in the response

How to get Cookies?

Let's see the simple code to get all the cookies.

1. Cookie ck[]=request.getCookies();
2. for(int i=0;i<ck.length;i++){
3. out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name
and value of cookie
4. }

21
J2EE
Q.8 Explain session on JSP
In such case, container creates a session id for each user.The container
uses this id to identify the particular user.An object of HttpSession can
be used to perform two tasks:

1. bind objects
2. view and manipulate information about a session, such as the
session identifier, creation time, and last accessed time.

How to get the HttpSession object ?

The HttpServletRequest interface provides two methods to get the object


of HttpSession:

1. public HttpSession getSession():Returns the current session


associated with this request, or if the request does not have a
session, creates one.
2. public HttpSession getSession(boolean create):Returns the
current HttpSession associated with this request or, if there is no
current session and create is true, returns a new session.

Commonly used methods of HttpSession interface


1. public String getId():Returns a string containing the unique
identifier value.
2. public long getCreationTime():Returns the time when this
session was created, measured in milliseconds since midnight
January 1, 1970 GMT.
3. public long getLastAccessedTime():Returns the last time the
client sent a request associated with this session, as the number of
milliseconds since midnight January 1, 1970 GMT.
4. public void invalidate():Invalidates this session then unbinds any
objects bound to it.

index.html

22
J2EE
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
welcome.jsp
1. <html>
2. <body>
3. <%
5. String name=request.getParameter("uname");
6. out.print("Welcome "+name);
8. session.setAttribute("user",name);
10. <a href="second.jsp">second jsp page</a>
12. %>
13. </body>
14. </html>
second.jsp
1. <html>
2. <body>
3. <%
5. String name=(String)session.getAttribute("user");
6. out.print("Hello "+name);
8. %>
9. </body>
10. </html>

Q.9 discuss Exception Handling in JSP

23
J2EE
The exception is normally an object that is thrown at runtime. Exception
Handling is the process to handle
the runtime errors. There may occur exception any time in your web
application. So handling exceptions is as afer side for the web developer.
In JSP, there are two ways to perform exception handling:
1. By errorPage and isErrorPage attributes of page directive
2. By <error-page> element in web.xml file
Example of exception handling in jsp by the elements of page
directive
In this case, you must define and create a page to handle the exceptions,
as in the error.jsp page. The pages
where may occur exception, define the errorPage attribute of page
directive, as in the process.jsp page.
There are 3 files:
· index.jsp for input values
· process.jsp for dividing the two numbers and displaying the result
· error.jsp for handling the exception
index.jsp
1. <form action="process.jsp">
2. No1:<input type="text" name="n1" /><br/><br/>
3. No1:<input type="text" name="n2" /><br/><br/>
4. <input type="submit" value="divide"/>
5. </form>
process.jsp
1. <%@page errorPage="error.jsp" %>
2. <%
3.
4. String num1=request.getParameter("n1");
5. String num2=request.getParameter("n2");
6.
7. int a=Integer.parseInt(num1);
8. int b=Integer.parseInt(num2);
9. int c=a/b;
10. out.print("division of numbers is: "+c);
11.
24
J2EE
12. %>
error.jsp
1. <%@page isErrorPage="true" %>
2.
3. <h3>Sorry an exception occured!</h3>
4.
5. Exception is: <%= exception %>

Q.10 javabean
A JavaBean is a Java class that should follow the following conventions:

o It should have a no-arg constructor.


o It should be Serializable.
o It should provide methods to set and get the values of the
properties, known as getter and setter methods.

Why use JavaBean?

According to Java white paper, it is a reusable software component. A


bean encapsulates many objects into one object so that we can access
this object from multiple places. Moreover, it provides easy maintenance

JavaBean Properties or methods

A JavaBean property is a named feature that can be accessed by the user


of the object. The feature can be of any Java data type, containing the
classes that you define.

A JavaBean property may be read, write, read-only, or write-only.


JavaBean features are accessed through two methods in the JavaBean's
implementation class:

1. getPropertyName ()

25
J2EE
For example, if the property name is firstName, the method name would
be getFirstName() to read that property. This method is called the
accessor.

2. setPropertyName ()

For example, if the property name is firstName, the method name would
be setFirstName() to write that property. This method is called the
mutator.

Advantages of JavaBean
o The JavaBean properties and methods can be exposed to another
application.
o It provides an easiness to reuse the software components.

Disadvantages of JavaBean
o JavaBeans are mutable. So, it can't take advantages of immutable
objects.
o Creating the setter and getter method for each property separately
may lead to the boilerplate code.
o package mypack;
o public class Test{
o public static void main(String args[]){
o Employee e=new Employee();//object is created
o e.setName("Arjun");//setting value to the object
o System.out.println(e.getName());
o }}

Q.11 <jsp:useBean> action tag

The useBean action is quite versatile. It first searches for an existing


object utilizing the id and scope variables. If an object is not found, it
then tries to create the specified object.
The simplest way to load a bean is as follows −

26
J2EE
<jsp:useBean id = "name" class = "package.class" />
Once a bean class is loaded, you can
use jsp:setProperty and jsp:getProperty actions to modify and retrieve
the bean properties.
Q.12 Define Expression Language (EL) in JSP

The Expression Language (EL) simplifies the accessibility of data


stored in the Java Bean component, and
other objects like request, session, application etc.
There are many implicit objects, operators and reserve words in EL.
It is the newly added feature in JSP technology version 2.0.
Syntax for Expression Language (EL)
1. ${ expression }
Implicit Objects in Expression Language (EL)
There are many implicit objects in the Expression Language. They are as
follows:
Implicit Objects Usage
1. pageScope: it maps the given attribute name with the value set in
the page scope
2. requestScope: it maps the given attribute name with the value set
in the request scope
3. sessionScope: it maps the given attribute name with the value set
in the session scope
4. applicationScope: it maps the given attribute name with the value
set in the application scope
5. param: it maps the request parameter to the single value
6. paramValues: it maps the request parameter to an array of values
7. header: it maps the request header name to the single value
8. headerValues: it maps the request header name to an array of
values
9. cookie: it maps the given cookie name to the cookie value
10. initParam: it maps the initialization parameter

27
J2EE
11. pageContext: it provides access to many objects request,
session etc.

28

You might also like