Nearby lessons

26 of 30

JSP Examples - Standard Actions

📌 What You Will Learn
  • Wire JavaBeans into JSPs with standard actions
  • See bean rules (no-arg constructor, getters/setters) in practice
  • Deploy a complete bean-driven JSP app

Complete programs for the JSP standard actions: jsp:useBean, jsp:setProperty, jsp:getProperty, jsp:include, jsp:forward and jsp:plugin, with full JavaBean sources (CalculatorBean, CustomerBean).

Unit 2: JSP Standard Actions

2.<jsp:getProperty>

3.<jsp:setProperty>

We are generally using scripting elements in the JSP. This approach is very easy approach at

the beginners level.

test.jsp:

Example01
JCode Cell
1 
2<jsp:useBean> with attributes id, type, class and scope
3

Unit 2: JSP Standard Actions

This approach has several serious disadvantages...

  • There is no clear separation of presentation and business logic. The person who is writing

this JSP should have compulsory the knowledge of both java and html, which may not possible

always.

  • This approach does not promote reusability.
  • It reduces readability of the code also

We can resolve these problems by encapsulating total business logic inside Java Bean.

Example02
JCode Cell
1 
2<%!
3public int squareIt(int x)
4{
5return x*x;
6}
7%>
8<h1>
9The Square of 4 is :<%= squareIt(4) %></br>
10The Square of 5 is :<%= squareIt(5) %></br>
11</h1>
12

CalculatorBean.java

test.jsp:

Example03
JCode Cell
1 
2package pack1;
3public class CalculatorBean
4{
5public int squareIt(int i)
6{
7return i * i;
8}
9}
10

CalculatorBean.java

|-test.jsp

|-WEB-INF

|-classes

|-pack1

|-CalculatorBean.class

The advantages of this approach are:

  • Separation of Presentation and Business Logic

Presentation logic is available in the JSP, where as business Logic is available in the java class,

so that readability of the code will be improved.

  • Separation of Responsibilities

Java Developer can concentrate on business logic where as HTML Page Designer can

concentrate on Presentation Logic. As both can work simultaneously we can reduce project

development time.

  • It promotes reusability of the code

where ever squareIt() functionality is required we can use same bean without rewriting.

Eg: We can purchase a bean for File uploading and we can start uploading of files within

minutes...

Java Bean

Java Bean is a simple java class.

To use bean inside JSP,the bean class has to follow the following rules.

  • The class should contain public no-arg constructor. Otherwise <jsp:useBean> tag won't

work. Internally JSP Engine is responsible to create bean object. For this JSP Engine always

calls public no-arg constructor.

  • For every Property , Bean class should contain public getter and setter methods.JSP Engine

calls these methods to get and set properties of the bean. Otherwise <jsp:getProperty> and

<jsp:setProperty> tags won't work.

Example04
JCode Cell
1 
2<jsp:useBean id="c" class="pack1.CalculatorBean" />
3<h1>The square of 4 is :<%= c.squareIt(4) %> <br>
4<h1>The square of 5 is :<%= c.squareIt(5) %> <br>beanex1
5

CalculatorBean.java

We can use this tag to make bean object available to the JSP.

There are 2 forms of <jsp:useBean>

  • without body:

<jsp:useBean id="c" class="pack1.CalculatorBean" scope="request" />

  • with body:
Example05
JCode Cell
1 
2Bean Related Tags : <jsp:useBean>
3

CalculatorBean.java

The main objective of body is to perform initialization for newly created bean object..

If the bean object is already available then <jsp:useBean> won't create any new Object and it

will use existing object only. At this time body won't be executed.

<jsp:useBean id="c" class="pack1.CalculatorBean" scope="request" />

Attributes of <jsp:useBean>:

<jsp:useBean> can accept the following 5 attributes

Example06
JCode Cell
1 
2<jsp:useBean id="c" class="pack1.CalculatorBean" >
3body
4</jsp:useBean>
5

CalculatorBean.java

  • id:

This attribute represents the name of the reference variable of the Bean object.

By using this id only we can access bean in rest of the JSP.

The id attribute is mandatory.

Eg: <jsp:useBean id="p" class="Student" type="Person" />

The equivalent java code is : Person p = new Student();

  • class:

This attribute specifies the fully qualified name of java bean class.

For this class only JSP Engine will perform instantiation. Hence it should be concrete class and

we cannot use abstract class and interfaces.

Bean class should compulsory contains public no-arg constructor. Otherwise we will get

Instantiation problems.

This attribute is optional & whenever we are not using class attribute compulsory we should

use type attribute. In this case <jsp:useBean> won't create any new object and it will always

returns existing bean object only.

  • type:

This attribute can be used to specify the type of reference variable.

The value of type attribute can be concrete class or abstract class or interface.

type attribute is optional, but at that time compulsory we should specify class attribute.

  • scope:

This attribute specifies in which scope the JSP Engine has to search for the required bean

object.

In that scope if the bean object is not already available then JSP engine will create a new bean

object & stores that object in the specified scope for the future purpose.

The allowed values for the scope attribute are: page,request,session and application.

The scope attribute is optional & default value is page scope.

Eg: <jsp:useBean id="c" class="pack1.CalculatorBean" scope="request" />

The equivalent java code is:

Example07
JCode Cell
1 
2id
3class
4type
5scope
6beanName
7

CalculatorBean.java

//now bean object is available

To use session scope compulsory session object should be available in the JSP. otherwise we

will get error.

Eg:

Example08
JCode Cell
1 
2CalculatorBean c=null;
3c=(CalculatorBean)pageContext.getAttribute("c",2);
4if(c==null)
5{
6c = new CalculatorBean();
7pageContext.setAttribute("c",c,2);
8}
9

CalculatorBean.java

Error: Illegal for useBean to use session scope when JSP page declares (via page directive)

that it does not participate in sessions

  • beanName:

There may be a chance of using Serialized bean from local file system. In this case we have to

use beanName attribute.

Various possible combinations:

  • id attribute is mandatory
  • scope attribute is optional and default scope is page scope

3.The attributes class, type, beanName can be used in the following combinations:

a) class

b) type

c) class , type

d) type, beanName ( beanName always associated with type but not class)

  • If class attribute is used, whether we are using type attribute or not, it should be concrete

class & should contain public no-arg constructor.

Eg:

<jsp:useBean id="c" class="java.lang.Runnable" />

Error:The value for the useBean class attribute java.lang.Runnable is invalid.

  • If we are using only type attribute without class attribute, compulsory bean object should

be available in the specified scope. Otherwise we will get InstantiationException.

Eg:

<jsp:useBean id="c" type="java.lang.Runnable" />

In this case compulsory Runnable Type object should be available in page scope otherwise we

will get: java.lang.InstantiationException: bean c not found within scope

Q. Consider the class

package pack1;

public class CustomerBean

{

}

Assume that no CustomerBean object is already created. Which of the following standard

action creates a new instance of this and store in the request scope.

Example09
JCode Cell
1 
2<%@ page session="false" %>
3<jsp:useBean id="c" class="pack1.CalculatorBean" scope="session" />
4

CalculatorBean.java

We can use this standard action to get properties of the bean object.

Eg:

<%

CustomerBean c = new CustomerBean();

out.println(c.getName());==>getting and printing

%>

equivalent code is

<jsp:useBean id="c" class="CustomerBean" />

<jsp:getProperty name="c" property="name" />

<jsp:getProperty> contains the following 2 attributes

  • name:

The name of bean instance from which required property has to get.

It is exactly equal to id attribute of <jsp:useBean>

  • property:

The name of java bean property which has to retrieve.

Both attributes are mandatory.

Note:

<jsp:getProperty> tag internally calls getter method. Hence bean class should compulsory

contains corresponding getter method. otherwise <jsp:getProperty> tag won't work.

Demo Program for <jsp:useBean> and <jsp:getProperty>:

test.jsp:

Example10
JCode Cell
1 
2<jsp:useBean name="c" type="pack1.CustomerBean" />
3<jsp:makeBean name="c" type="pack1.CustomerBean" />
4<jsp:useBean id="c" class="pack1.CustomerBean" scope="request" />
5<jsp:useBean id="c" type="pack1.CustomerBean" scope="request" />
6Bean Related Tags : <jsp: getProperty >
7

CalculatorBean.java

Example11
JCode Cell
1 
2<jsp:useBean id="c" class="pack1.CustomerBean" />
3<h1>
4Customer Name:<jsp:getProperty name="c" property="name"/><br>
5Customer Mail:<jsp:getProperty name="c" property="mail"/>
6</h1>
7

CustomerBean.java

beanex2

|-test.jsp

|-WEB-INF

|-classes

|-pack1

|-CustomerBean.class

Example12
JCode Cell
1 
2package pack1;
3public class CustomerBean
4{
5private String name="durga";
6private String mail="durgaocjp@gmail.com";
7public String getName()
8{
9return name;
10}
11public String getMail()
12{
13return mail;
14}
15}
16

CustomerBean.java

This standard action can be used to set properties of bean object.

We can use <jsp:setProperty> in the following forms:

<jsp:useBean id="c" class="CustomerBean" />

1.<jsp:setProperty name="c" property="name" value="durga"/>

c.setName("durga");

Example13
JCode Cell
1 
2Bean Related Tags : <jsp: setProperty >
3

CustomerBean.java

c.setName(req.getParameter("uname"));

It retrieves the value of specified request parameter and assign its value to the specified bean

property.

  • If the request parameter name matches with bean property name, then no need to use

param attribute.

<jsp:setProperty name="c" property="name" />

c.setName(req.getParameter("name"));

Example14
JCode Cell
1 
2<jsp:setProperty name="c" property="name" param="uname"/>
3

CustomerBean.java

* specifies all properties of the bean.

It iterates through all request parameters and if any parameter name matched with bean

property name then it assigns request parameter value to the bean property.

Attributes of <jsp:setProperty>:

  • name:

It refers the name of bean object whose property has to set. This is exactly same as id

attribute of <jsp:useBean>. It is mandatory attribute.

  • property:

The name of the java bean property which has to be set. It is mandatory attribute.

  • value:

It specifies the value which has to set to the java bean property.

It is optional attribute and never comes together with "param" attribute.

  • param:

This attribute specifies the name of request parameter whose value has to set to the bean

property. It is optional attribute and should not come together with value attribute.

Demo Program-1 for <jsp:useBean> ,<jsp:getProperty> and <jsp:setProperty>:

login.html:

Example15
JCode Cell
1 
2<jsp:setProperty name="c" property="*" />
3

CustomerBean.java

Example16
JCode Cell
1 
2<html>
3<body><h1>
4<form action="test.jsp">
5Name : <input type="text" name="name"><br>
6Mail : <input type="text" name="mail"><br>
7Age : <input type="text" name="age"><br>
8<input type=submit >
9</form></h1>
10</body>
11</html>test.jsp:
12<jsp:useBean id="c" class="pack1.CustomerBean" />
13<jsp:setProperty name="c" property="*" />
14<h1>Plz confirm your provided values...<br>
15Customer Name: <jsp:getProperty name="c" property="name" /><br>
16Customer Mail: <jsp:getProperty name="c" property="mail" /><br>
17Customer Age: <jsp:getProperty name="c" property="age" /> </h1>
18

CustomerBean.java

beanex3

|-login.html

|-test.jsp

|-WEB-INF

|-classes

|-pack1

|-CustomerBean.class

Demo Program-2 for <jsp:useBean> ,<jsp:getProperty> and <jsp:setProperty>:

login.html:

Example17
JCode Cell
1 
2package pack1;
3public class CustomerBean
4{
5private String name;
6private String mail;
7private int age;
8public String getName()
9{
10return name;
11}
12public String getMail()
13{
14return mail;
15}
16public int getAge()
17{
18return age;
19}
20public void setName(String name)
21{
22this.name = name;
23}
24public void setMail(String mail)
25{
26this.mail= mail;
27}
28public void setAge(int age)
29{
30this.age = age;
31}
32}
33

CustomerBean.java

Example18
JCode Cell
1 
2<html>
3<body><h1>
4<form action="test.jsp">
5Name : <input type="text" name="name"><br>
6Mail : <input type="text" name="mail"><br>
7Age : <input type="text" name="age"><br>
8<input type=submit >
9</form></h1>
10</body>
11</html>test.jsp:
12<jsp:useBean id="c1" class="pack1.CustomerBean" >
13<jsp:setProperty name="c1" property="*" />
14</jsp:useBean>
15 
16<h1>Please check your values and confirm<hr>
17Name:<jsp:getProperty name ="c1" property="name" /><br>
18Mail:<jsp:getProperty name ="c1" property="mail" /><br>
19Age: <jsp:getProperty name ="c1" property="age" /><br>
20</h1>
21

CustomerBean.java

beanex4

|-login.html

|-test.jsp

|-WEB-INF

|-classes

|-pack1

|-CustomerBean.class

Note:

If any type of conversions are required then all these conversions will takes care by bean

related tags.

(String to int)

Developing Reusable Web Components

We can develop reusable web components by using the following standard actions.

1.<jsp:include>

2.<jsp:forward>

3.<jsp:param>

1.<jsp:include>:

<jsp:include page="header.jsp" flush="true"/>

The response of header.jsp will be included in the current page response at request

processing time. Hence it is dynamic include.

This is the tag representation of pageContext.include()

This standard action contains the following 2 attributes.

  • page:

represents the name of the included page. It is mandatory attribute.

  • flush:

It specifies whether the response will be flushed before inclusion or not.

It is optional attribute and default value is false.

Example19
JCode Cell
1 
2package pack1;
3public class CustomerBean
4{
5private String name;
6private String mail;
7private int age;
8public String getName()
9{
10return name;
11}
12public String getMail()
13{
14return mail;
15}
16public int getAge()
17{
18return age;
19}
20public void setName(String name)
21{
22this.name = name;
23}
24public void setMail(String mail)
25{
26this.mail= mail;
27}
28public void setAge(int age)
29{
30this.age = age;
31}
32}
33

Demo Program

Note:

In JSPs,we can perform include by using the following 4 ways...

1.include directive:

<%@ include file="header.jsp" %>

2.include action:

<jsp:include page="header.jsp" />

3.By using pageContext implicit object:

<%

pageContext.include("header.jsp");

%>

4.By using RequestDispatcher:

<%

RD rd = request.getRD("header.jsp");

rd.include(request,response);

%>

Example20
JCode Cell
1 
2<jsp:include page="header.jsp" />
3Offered courses are :Java,.Net,Testing...
4<jsp:include page="footer.jsp"/>
5

Demo Program

If the first JSP is responsible for some preliminary processing & Second JSP is responsible for

providing complete response, then we should go for forward mechanism.

syntax:

<jsp:forward page="second.jsp" />

first.jsp:

Example21
JCode Cell
1 
2<jsp:forward>:
3

Demo Program

<h1>This is Second JSP</h1>

Note: In JSPs we can implement forward mechanism in the following 3 ways.

  • forward action:

<jsp:forward page="second.jsp" />

  • By using pageContext implicit object:

<%

pageContext.forward("second.jsp");

%>

  • By using RequestDispatcher:

<%

RD rd = request.getRD("second.jsp");

rd.forward(request,response);

%>

Example22
JCode Cell
1 
2<h1>This is First JSP</h1>
3<jsp:forward page="second.jsp" />second.jsp:
4

Demo Program

while forwarding or including, we are allowed to send parameters to the target JSP.For this we

have to use <jsp:param> tag.

<jsp:param name="c1" value="JAVA" />

<jsp:param> contains the following 2 mandatory attributes

  • name:

It represents the name of the parameter

  • value:

It represents the value of the parameter

The parameters which are sending by using <jsp:param> tag are available as form parameters

in the target jsp.

first.jsp:

Example23
JCode Cell
1 
2<jsp:param>
3

Demo Program

Case-1:

<jsp:forward page="http://localhost:7777/jsp2/second.jsp" />

<jsp:include page="http://localhost:7777/jsp2/second.jsp" />

<%@ include file="http://localhost:7777/jsp2/second.jsp" %>

The value of the file & page attributes should be relative paths only. We are not allowed to

use protocol, server port etc..otherwise we will get 404 status code.

Case-2:

<jsp:forward page="/test" />

<jsp:include page="/test" />

<%@ include file="/test" %>

In the case of forward and include actions, the attribute page can pointing to a servlet.

But in case of include directive, file attribute cannot pointing to a servlet. It can point to html,

jsp etc..

Case-3:

<jsp:forward page="second.jsp?c1=java&c2=Tesing" />

<jsp:include page="second.jsp?c1=java&c2=Tesing" />

<%@ include file="second.jsp?c1=java&c2=Tesing" %>

In the case of forward and include actions, we are allowed to pass query string.

But in the case of include directive, we are not allowed to pass query string.

Example24
JCode Cell
1 
2<jsp:include page="second.jsp">
3<jsp:param name="c1" value="JAVA" />
4<jsp:param name="c2" value="TESTING" />
5</jsp:include>second.jsp:
6<h1>The offered courses are :
7<%= request.getParameter("c1") %> and
8<%= request.getParameter("c2") %>
9</h1>Conclusions:
10

Demo Program

We can use <jsp:plugin> to plugin applet in the JSP.

  • Unused Standard Actions : <jsp:fallback>

We can use <jsp:fallback> inside <jsp:plugin> to print information if browser won't provide

support for applet.

Example25
JCode Cell
1 
2Unused Standard Actions : <jsp:plugin>
3

Demo Program

We can use <jsp:params> inside <jsp:plugin> to send parameters from the JSP to the applet.

main.jsp:

Example26
JCode Cell
1 
2Unused Standard Actions : <jsp:params>
3

Demo Program

Example27
JCode Cell
1 
2<jsp:plugin
3type="applet"
4code="MyApplet.class"
5codebase="/plugindemo">
6 
7<jsp:params>
8<jsp:param name="username" value="durga" />
9</jsp:params>
10 
11<jsp:fallback>
12<p>Could not load applet!!!!</p>
13</jsp:fallback>
14 
15</jsp:plugin>
16

MyApplet.class

plugindemo

|-main.jsp

|-MyApplet

http://localhost:7777/plugindemo/main.jsp

Summary of JSP Standard Actions

Standard ActionDescriptionAttributes
Example28
JCode Cell
1 
2import java.awt.BorderLayout;
3import java.awt.Color;
4import java.awt.Font;
5 
6import javax.swing.JApplet;
7import javax.swing.JLabel;
8 
9public class MyApplet extends JApplet {
10 
11private JLabel label = new JLabel();
12 
13public void init() {
14label.setHorizontalAlignment(JLabel.CENTER);
15label.setFont(new Font("Arial", Font.BOLD, 20));
16label.setForeground(Color.BLUE);
17 
18setLayout(new BorderLayout());
19add(label, BorderLayout.CENTER);
20}
21 
22public void start() {
23String firstName = getParameter("username");
24label.setText("Hello " + firstName);
25}
26}
27

MyApplet.class

To get and Print Propertiesname, property
Example29
JCode Cell
1 
2<jsp:useBean>
3<jsp:getProperty> To Make Bean Object id, class, type, scope,
4<jsp:getProperty> available to the JSP beanName
5<jsp:include>
6

MyApplet.class

To set the Propertiesname, property, value,
7) <jsp:plugin>of Beanparam
Example30
JCode Cell
1 
2<jsp:forward> of Bean
3<jsp:param>
4

MyApplet.class

To include the Response ofpage, flush
9) <jsp:params>Target JSP at Request processing

Time

To forward a Request from onepage

JSP to another JSP

To send Parameters to thename, value

Target JSP while performing

forward and include

To plug in Applet in our JSPtype, code, codeBase......

To display some Message if

Browser won't provide SupportN/A

for Applets

To send Parameters from JSP toN/A

Applet

Example31
JCode Cell
1 
2<jsp:fallback>
3
📝 Key Takeaways
  • jsp:useBean needs id + class or type + scope
  • JavaBeans need a public no-arg constructor
  • Standard actions separate presentation from business logic