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

Java Beans and JSP Actions

The document discusses Java beans and JSP action tags in Java. It begins by defining what a Java bean is - a plain Java class used to store details of real-world entities. It then covers Java bean design conventions like properties, getter and setter methods. The document also discusses the need for beans in JSP for collectively storing information and transferring data between JSP pages. Finally, it introduces JSP action tags which are predefined tags that perform common tasks like instantiating beans, setting/getting bean properties, and forwarding requests to reduce Java code in JSP pages.

Uploaded by

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

Java Beans and JSP Actions

The document discusses Java beans and JSP action tags in Java. It begins by defining what a Java bean is - a plain Java class used to store details of real-world entities. It then covers Java bean design conventions like properties, getter and setter methods. The document also discusses the need for beans in JSP for collectively storing information and transferring data between JSP pages. Finally, it introduces JSP action tags which are predefined tags that perform common tasks like instantiating beans, setting/getting bean properties, and forwarding requests to reduce Java code in JSP pages.

Uploaded by

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

Advance Java

Java Beans and JSP Actions

LEVEL – PRACTITIONER
About the Author

Created By: Renjith(t-renjith)/ Shanmu (105110)

Credential Trainer / Sr Architect


Information:

Version and 1.0, January 16’th 2012


Date:

2
Icons Used

Hands on
Questions Tools Exercise

Coding Test Your Case Study


Standards Understanding

Best Practices
Demonstration & Industry
Workshop
Standards

3
Objectives

After completing this chapter you will be able to understand:


What is a java bean?
What is JSP action tag?
Type of JSP action tags.
How to use JSP action tags?

4
What is server side java bean ?

 A server side java bean is a class used to store the details of real
world entities
Example: Employee  Employee Name and Employee Salary,
Student  Student Name, Student Address.
 Bean is a plain java class which contains
 Fields (or) Properties: Fields to store the data, example:
Employee Name, Salary.
 Methods: Methods for retrieving and modifying the attributes
like setEmployeeName(), setStudentAddress(). The methods
are referred to as accessors/mutator.

5
Java Bean design conventions

• A JavaBean component property can be read/write, read-only, or write-only.


• The bean property needs to be accessible using public methods.
 For each readable property, the bean must have a method as illustrated below to
retrieve the property value

Syntax:
Public Datatype get<PropertyName> {
return value; // Returns the property value
}

Example:
Public int getEmployeeId {
return empId; // Returns the employee id value
} 6
Java Bean design conventions

 For each writable property, the bean must have a method as illustrated below,

Syntax:
Public set<PropertyName>(Datatype newValue) {
property= newValue; // sets the new value into the property
}

Syntax:
Public setEmployeeId(int newEmpId) {
empId= newEmpId; // sets the new employee id into the
employee id property
}

7
Sample Bean Class

The bean properties User Name and password.


Declared private.

Getter method for retrieving the user name.


Declared Public.

Setter method for modifying user name.


Declared Public.

Note the getter and setter names convention


is
1. get + property name with the first letter
of the property name capitalized
and
2. set+ property name with the first letter of
the property name capitalized .

8
Why to follow naming convention for methods?

The web container maps the request attribute with the method names and
triggers the appropriate methods for retrieving or setting the values.
Example:
Request Attribute Name: empId
Method Triggered: setEmpId(), getEmpId()

NOTE: Web container automatically capitalizes the first character of the


attribute name and concatenates “set” (or) “get” to it for either setting or
retrieving property values in bean.

How is this done?


This is done using reflection and introspection.
Reflection & introspection are java API’s used for finding the properties and
methods of a class and invoking it dynamically.

Reflection is out of scope in CATP program. If interested


trainees can explore this on their own.

9
Easy steps for creating Beans using SDE

Step 1 : Create a class named User


Step 2 : Declare two properties for the class
1. userName – type String.
2. Password - type String.
Step 3 : Right click source 
source generate getter and setter

10
Easy steps for creating Beans using SDE
(Cont)

Select the properties and the


accessor methods to be generated
and click Ok.

11
Need for Beans in JSP

 Beans are used to JSP for collectively storing some information .

 Beans makes transfer of data between JSP’s easier.

 For example if you are handling with a registration form all the registration details
can be loaded into a RegistrationBean and can be transported across other
components as a single object.

12
Need for Beans in JSP

How to set value to a Bean ?


Values can be set to the bean using the setter method .
userBean.setName(request.getParameter(“name”));
Reads the parameter name from the request and sets it to the property
name in userBean.

How to read values from a bean ?


Values can be retrieved from a bean using the getter method .
String userName=userBean.getName();
Reads the property value name from the bean and assigns it to a
variable.

13
Lend a Hand : Using Java beans in JSP

In this demo we are going to familiarize how java beans are used with jsp.
We are going to develop a login page and validate the credentials and
redirect the response to success or error page.
Components
1 . login.jsp : login page
2 . success.jsp : Success page
3 . User.java : The user bean class.
The login.jsp will validate the user name/password , create a user bean if
successful redirect it to success page. Success page should access the
bean properties and display it on the screen.

14
Lend a Hand – login.jsp

We will create a login page as shown below,


1. User Name – Text Field
2. Password – Password Field
3. Login - Submit button

15
Lend a Hand – Develop login.jsp

Sets the values to the bean using the setter


methods

Reads the values to the bean


using the getter methods

Sets the bean as a request


attribute

16
Lend a Hand – Develop user Bean

Develop the user bean as mentioned below.

17
Lend a Hand – Develop success.jsp

Welcome TOM

Reads the bean object from request and type


casts it.

Reads the username from the bean using getter


method.

18
Lend a Hand – Invalid Login

In case of invalid login redirect the request to login page


and display the error message.

19
Lend a Hand : Deploy and Run

Step 1 : Deploy and run the application


Step 2 : Call login.jsp from the browser
http://localhost:8080/ActionDemo/login.jsp
Step 3 : Enter user name and password as “tom” & “jerry” and click
login. The success page should be displayed.
Step 4: Enter a invalid user name and password the control should be
redirected to a error page.

20
What is JSP action tag ?

JSP action tags are a set of predefined tags provided by the JSP
container to perform some common tasks thus reducing the java code in
JSP.

Some of the common tasks are,

 Instantiate java bean object.

 Setting values to beans.

 Reading values from beans.

 Forward the request to another resource.

 Including another resource.


21
jsp action tag syntax

<jsp:action_name attribute="value" />

Where,

action_name : specifies the name of the action to be performed

attribute : specifies the attributes relevant to the action.

Example:

<jsp:include page=“myPage.jsp” />

Where “include” is the action and “page” is the attribute of the


action include, this performs the include action of including a JSP page.

22
Action tags in JSP

The following are the action tags available in JSP

 jsp:include  jsp:element
 jsp:forward  jsp:body
 jsp:usebean  jsp:text
 jsp:setProperty  jsp:attribute
 jsp:getProperty  jsp:param
 jsp:fallback  jsp:plugin

The highlighted ones will be covered in detail in the coming slides.

23
JSP:include

 Used for dynamically including the pages


 Includes the output of the included page during run time
 Contents of the page are not included – Only the response is included.

Assume footer.jsp is included homepage.jsp

R
R E
E S 5
Q The footer JSP response is
2 P included in the home page and
U O
E response sent to client.
Home page N
1 translated to S S
homepage.java by T E 4
web container.
homepage.jsp homePage_jsp.java footer_jsp.java
3
Home page
requests footer
24
JSP file.
Jsp:include tag

Syntax :

<jsp:include page=“PageName” />

Example : Assume that the following line is included in index.jsp

<jsp:include page=“myPage.jsp” />

Here the myPage.jsp response is included in the index.jsp

25
Directive Vs Action include

Consider a scenario in which we are asked to create a login application . They have
the following requirements
 Home page is common for all categories of employees
 The heading is different for different designation of employees and should be
included in all the pages based on the employee designation
 The footer page is common for all and should be include in all the pages .

Given the above scenario,


 What is the include mechanism you will use to include the heading page ?
 What is the include mechanism you will use to include the footer ?

26
Difference between directive and action include

Manager Request Login


Login.jsp

Login success. User redirected to home page

To be included using
footer.html directive include

Home.jsp (with Home_java.jsp home.jsp


footer.html)
+ During the first request the
managerHeading.jsp Includes page is translated into a servlet
managerHeading.jp .The files included using
since manager has directive include gets included
logged in at this translation stage.

managerHeading.jsp traineeHeading.jsp

To be included dynamically based on the employee designation


27
jsp:forward

The forward action tag is used to transfer control to a static or dynamic resource.
 The forward action terminates the action of the current page and forwards the
request to another resource such as a static page, another JSP page, or a Java
servlet.
 The static or dynamic resource to which control has to be transferred is
represented as a URL.
 The user can have the target file as an HTML file, another JSP file, or a servlet.

28
jsp:forward Syntax

Syntax:
<jsp:forward page=“URL" />
Forwards the request to the specified URL.
Example :
<jsp:forward page=“success.jsp" />
Forwards the request to the success.jsp
When used?
 Provides the same functionality of the forward() method inRequestDispatcher
interface
 Used for forwarding request from one JSP to another .

29
jsp:Param

The jsp:param action is used to add the specific parameter to current


request.
 The jsp:param tag can be used inside a jsp:include (or) jsp:forward.
Syntax:
  <jsp:forward page =“URL" />
      <jsp:param   name =“paramName”   value="parameterValue”/>
</jsp:forward>
 <jsp:include page =“URL" />
      <jsp:param name =“paramName“   value="parameterValue”/>
</jsp:include>

30
jsp:Param Example

A Scenario: Consider a scenario on successful login the user needs to be forwarded


to the success page with the user name set as an parameter to the request object so
that name can be accessed in the home page and displayed.

Jsp:Param can be used along with jsp:Forward as shown


 <jsp:forward page =“success.jsp" />
      <jsp:param   name =“userName”   value=“<name>”/>
</jsp:forward>
Where
success.jsp : success page
userName : Request attribute Name
name : The variable containing the user’s name
31
jsp:useBean

The <jsp:useBean> tag attempts to locates a bean or if the Bean does not exist,
instantiates it from the class specified.
Syntax: <jsp:useBean id="name" class="package.class“
scope=“request/session/page/application“ />

Where ,
Id – The name used for referring for the bean object
Class – The Bean Class
Scope - The scope in which the bean object is available

32
Other Attributes for useBean action tag

Attribute Description
Gives a name to the variable that will reference the bean. A previous bean object
id is used instead of instantiating a new one if one can be found with the same id and
scope.
Instantiates a Bean from a class, using the new keyword and the class constructor.
class The class must not be abstract and must have a public, no-argument constructor.
The package and class name are case sensitive.
scope="page|request|session|application"
scope
Defines a scope in which the bean exists .The default value is page.
If the Bean already exists in the scope, gives the Bean a data type other than the
type class from which it was instantiated. If you use type without class or beanName,
no Bean is instantiated. The package and class name are case sensitive.
Gives the name of the bean, as you would supply it to the instantiate method of
beanName
Beans.

33
How jsp:useBean works?

Example : <jsp:useBean id=“user" class=“com.catp.beans.UserBean“


scope=“request “ />

How it works? Sequence of steps,


1. Attempts to locate a Bean with the name “UserBean” in the request scope.
2. If it finds the Bean, stores a reference in the variable user.
3. If it does not find the Bean, instantiates a bean using the class UserBean,
and stores the reference to the variable user.

34
Bean Object Scopes

 page :is available only within the JSP page and is destroyed when
the page has finished generating its output for the request.
 request : valid for the current request and is destroyed when the
response is sent
 session : valid for a user session and is destroyed when the
session is destroyed
 application : valid throughout the application and is destroyed
when the web application is destroyed/uninstalled.

35
jsp:setProperty

The setProperty action sets the properties of a Bean. The Bean must have been
previously defined before this action.
Syntax:
<jsp:useBean id="myName" class=“package.class” />
<jsp:setProperty name="myName" property="someProperty”
value =“someValue” />
Where,
name : the name of the bean object and should be the same as the id value specified in
usebean
property :the bean property (field name) for which the value is to be set. There should
be a instance variable with the property name specified and accessors/mutator
methods.
value : the value to be set for the property .
36
jsp:setProperty mapping HTML forms

The following options can be used to automatically set the values from an HTML form to
a java bean using the setProperty action.

Option 1
<jsp:setProperty name=“UserBean" property="someProperty” param =“userName” />

Sets the value of the HTML form element with the name userName into the bean UserBean’s
property someProperty.

Option 2
<jsp:setProperty name="myName" property="*” />

Sets all the values of the form elements into the bean properties.

In this case the name of the property and the name of the form element should be the same

37
Example for jsp.setProperty usage

HTML form UserBean

38
jsp:getProperty

The getProperty action is used to retrieve the value of a given property and
converts it to a string, and finally inserts it into the output.
Syntax:
<jsp:useBean id=“myName” type=“package.class” />
<jsp:getProperty name="myName" property="someProperty" />
Where,
name : Bean name same as the id specified in the usebean action
property : The bean property name whose value is to be retrieved

39
jsp:getProperty Example

Example:
<jsp:useBean id=“user” type=“com.catp.beans.UserBean” />
<jsp:getProperty name=“user" property=“userName" />

This Reads the value of the property named userName from the
UserBean and prints it

40
Recap: JSP Action tags

JSP Action tags Description


jsp:include For including a page dynamically in a parent page.
jsp:forward For forwarding the request to a another resource.

jsp:usebean To reference a bean and use its properties.

jsp:setProperty Set the value of a property referred using use bean.

jsp:getProperty Gets the property value of a bean referred in use bean tag.

jsp:Param Used to share parameter and its value with the page being
included or forwarded.

41
Time To Reflect

Associates to quickly summarize the following before ending the session


 What is a java bean?

 What is the difference between action and directive include?

 What is the action tag used for setting a beans property value?

 What is the action tag used for forwarding the request?

 What is the action tag used for including a page?

 What is the action tag used for mapping HTML form elements with the bean.?

42
Lend a Hand : Action Tags

Using this demo the associates gets familiarized with the following action
tags in JSP
 jsp:include
 jsp:param
 jsp:useBean
 jsp:setProperty
 jsp:getProperty
 jsp:forward

43
Lend a Hand - Requirement

Consider a scenario in which ABC Soft corp have approached you to create a
registration form for their Employees for maintaining profile of each employee in the
company.
The requirement is as slated below
 There are three designation of employees
a)Manager
b)Developer
c)Trainee
 Employees should enter details in the registration form
 On successful entry the employee is forwarded to their respective home pages.

44
Lend a Hand- Requirement (Cont)

 The heading of the home page will be based on the designation of the
employee.
 The heading should be dynamically loaded based on designation of employee.
 A welcome message should be present in the home page.
Components
1. Registration.jsp : Registration page used by employees to register.
2. Success.jsp : Common Home page for all employees.
3. traineesHeading.jsp : Heading page for trainee’s success page.
4. developersHeading.jsp : Heading page for developer’s success page.
5. managersHeading.jsp : Heading page for manager’s success page.
6. Employee.java : The java bean class for storing the employee details.

45
Lend a Hand : Registration page Design

Create registration page as shown below

Should have three values


Manager, Trainees,
Developer.

46
Lend a Hand : Registration.jsp code

Instantiates bean using useBean


action and sets the value using
setProperty action.

IMPORTANT: Ensure the name of


the form elements are same as the
bean property names. They are
case sensitive.

Use JSP:forward to
forward request to success
page and jsp:param to set
success message.

47
Lend a Hand – Develop User Bean

48
Lend a Hand- Success page Design

 Create a success page which includes the header page.


 The header page should be included based on the designation selected. Say
“Manager Home Page”, Trainee Home Page” (or) “Developer Home Page”
 The body of the success page should display all the details which the user
entered in registration page in a tabular format

49
Lend a Hand - Develop success.jsp

Use JSP:include to
include the respective
pages and use jsp:param
to set name value as a
parameter for heading
page to display.

Reads the value using


getProperty action and
prints it.

50
Lend a Hand – Develop traineesHeading.jsp

Access the parameter set


and print the message.

51
Lend a Hand – Develop managersHeading.jsp

52
Lend a Hand – Develop developersHeading.jsp

53
Lend a Hand – Deploy and Run

Step 1 : Deploy and run the application


Step 2 : Invoke the registration.jsp from the browser
http://localhost:8080/ActionDemo/registration.jsp
Step 3 : Enter the registration details, designation as manager and click
register.
Step 4 : The success page should be displayed with the manager header.
Continue step 3 and for 4 for Developer and Trainee designation. The screen
should display the appropriate header pages.

54
Advance Java

You have successfully completed –


JSP Actions

You might also like