Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Working with Java Bean components in JSP

In this section we are going to discuss about how java beans can make the development easy when integrated with JSP pages.

In this section we are going to discuss about how java beans can make the development easy when integrated with JSP pages. Before this, all the java coding is written using the scriptlets , expressions etc. But introducing java beans in jsp seperates the business logic from the front end coding. Let us dig in detail and learn more about integrating java beans in jsp , working with java bean properties , how a java bean can be made persistent.

Topics discussed in this section are:

  • What is a Java Bean?
  • How to embed java beans in a JSP file?
  • Working with bean properties
  • Java Bean scope in JSP

What is a Java Bean?

A java bean is a simple java component which should satisfy the below mentioned points.

  • A java bean should not have any public variables. All the variables should be accessed using the getter/setter methods.
  • Java bean constructor should be a no argument constructor. To meet this requirement better leave the file without creating any constructor with arguments or create a no argument constructor explicitly.

Below code fragment is an example of a basic bean.

Listing 1: Course.java - Java Bean

package com.javaBeans;

public class Course {
	
	private String title;
	private String code;
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}	
}

How to embed java beans in a JSP file?

Java beans can be directly integrated in the jsp page which gives the user a flexibility to work with java reusable java components.

Following JSP standard actions embed the Java bean in a JSP file.

  • <jsp:useBean>
  • <jsp:getProperty>
  • <jsp:setProperty>

Load Java bean inside a JSP:

To start working with java beans inside a jsppage , first the bean should be loaded into the page. Once the bean is loaded , the variable properties of the bean can be accessed.

Hence to load a bean the standard action is used. The basic syntax of the action is as follows:

<jsp:useBean id=”course1” class=”com.Course” />

Above syntax representation means that “instantiate an object of the class ‘Course’ , binding it to a variable name specified in the ‘id’ attribute”

Writing above syntax in a JSP page creates an object referencing to the class “Course” and the name of the object is “course1”.

<jsp:useBean> has some other attributes which provides additional benefits when creating a bean object.

<jsp:useBean> “scope” attribute allows the bean object to be sharable across the application.

Depending on the values of the scope attribute , if the bean is shared and has the same id and scope on the other page, the same bean object is associated to the other jsp page. The property values also persist the same when the same object is associated in different pages .

If the bean is not sharable or the id and scope are different <jsp:useBean> instantiates a new object of the class .

Working with bean properties :

After the bean gets loaded into the page, the properties can be accessed using the following standard actions.

  • <jsp:getProperty>
  • <jsp:setProperty>
  • <jsp:getProperty>

This standard action accesses a property of the bean to get the value and put inside a jsp page.

The basic syntax of the <jsp:getProperty> is as follows:

<jsp:getProperty name=”course1” property=”title”/>

The above syntax tells the compiler to get the value of the variable “title” of the object “course1”.

The attribute name in the above syntax represents the object created using the action. The value of the name attribute of the <jsp:getProperty> and the id attribute of the <jsp:useBean> property should be same to refer to the object created.

The attribute property holds the name of the any variable of the bean loaded.

To get all the properties of the bean inside the jsp page the syntax of the <jsp:getProperty> should be

<jsp:getProperty name = “course1” property=”*” />

The asterisk “*” mark tells the container to load all the variable values of the bean object inside the jsp page.

Let us look into an example on how to use "getProperty"

Step 1:

  • Create a package com.javaBeans .
  • Create a java bean by the name "Course" .
  • Declare and initialize two string variables "title" and "code".
  • Generate getter/setter methods for the variables created and save the file.

Listing 2: Initializing the variables "title" and "code" of the java bean "Course.java"

package com.javaBeans;

public class Course {
	
	private String title = "Enter a title";
	private String code = "Enter a code";
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	
	

}

Step 2:

  • Create a jsp page.
  • Load the bean using the and name the bean as "course" using "id" attribute.

Listing 3 : getPropertyEg.jsp - Getting the properties of the bean using the <jsp:getProperty>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="#99CCFF">
<jsp:useBean id="course" class="com.javaBeans.Course" />
<div><h3>
Below Course title and code are default values set in the bean.
</h3></div>
<jsp:getProperty name="course" property="title"/><br>
<jsp:getProperty name="course" property="code"/>
</body>
</html>
Result of the getPropertyEg.jsp -Showing the values of the properties

Figure 1: Result of the getPropertyEg.jsp -Showing the values of the properties "title" and "code" . The values are initialized in the bean as shown in the Listing 2.

<jsp:setProperty>

To modify (or) assign value to any variable of the bean object standard action is used . The basic syntax is as below

<jsp:setProperty name=”course1” property=”title” value=”JSP”/>

The above syntax tells the controller to assign a string “JSP” to the variable “title” of the bean object “course1”

The attributes “name” and “property” carry the same functionality as similar to the <jsp:getProperty> . The additional attribute “value” holds some data which should be assigned to the property.

Let us look into the example on how to use <jsp:setProperty> to assign any value to the bean properties.

Step 1:

  • Create a jsp page.
  • Load the bean using the <jsp:useBean> action and name the bean as "course1" using the "id" attribute.
  • Set the properties of the bean using the <jsp:SetProperty> as shown.
  • Print the variables again using the <jsp:getProperty> to check the new values of the bean.

Listing 4 : Hello.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Java Beans</title>
</head>
<body bgcolor="#99CCFF">
<jsp:useBean id="course1" class="com.javaBeans.Course" />
<jsp:setProperty name="course1" property="title" value="JSP" />
<jsp:setProperty name="course1" property="code" value="jspC001" />
<div><h3>
Here are the values set to the bean course1
</h3></div>
<jsp:getProperty name="course1" property="title"/><br>
<jsp:getProperty name="course1" property="code"/>
</body>
</html>
Result of the Hello.jsp - Instead of the default values printed as shown in Figure 1 , newly assigned values using the action jsp:setProperty are printed after the successful page run.

Figure 2 : Result of the Hello.jsp - Instead of the default values printed as shown in Figure 1 , newly assigned values using the action <jsp:setProperty> are printed after the successful page run.

Till now we have studied about setting the bean properties assigning some string values to the "value" attribute.

The bean properties can also be set using the request parameter i;e, the parameter values of the obtained from the requesting page. Below syntax shows about setting the parameter using request parameter.

<jsp:setParameter name="course"
			 property="title"
			 value=  '<% = request.getParameter("title") %>' />

But "request.getParameter" always returns a string object. If any property of the Java bean has a data type other than string, data type conversion should be done explicitly.

Let us assume that we have an additional parameter "numberOfStudents" in the Course.java whose data type is integer.

To set the value of the property "numberOfStudents" using the request parameter following type conversion should be done explicitly.

<%
int studentNumber = 0;
try {
 studentNumber = 
 Integer.parseInt(request.getParameter("numberOfStudents"));
} catch(NumberFormatException nfe) {}
%>

<jsp:setProperty name="course"
			 property=" numberOfStudents "
			 value=  '<% = request.getParameter("studentNumber ") %>' />

Instead of doing all the above coding <jsp:setProperty> has an additional attribute called as "PARAM" . This attribute takes the name of the request parameter and does the conversion automatically without any explicit conversion.

Basic syntax of the attribute "PARAM" usage is as shown

<jsp:setProperty name="course"
			 property=" numberOfStudents "
			 param="studentNumber" />

From the above syntax "numberOfStudents" property of the bean is directly set to the value of the request parameter "studentNumber" .

Let us go through the concept with the help of an example.

Step 1:

  • Modify the existing bean by adding an additional variable whose data type is an "int".
  • Generate getter/setter methods for the new variable added.

Listing 5: Course.java - Added a new variable "numberOfStudents" which holds a value of number of students taken the course.

package com.javaBeans;

public class Course {
	
	private String title;
	private String code;
	private int numberOfStudents ;
	
	public int getNumberOfStudents() {
		return numberOfStudents;
	}
	public void setNumberOfStudents(int numberOfStudents) {
		this.numberOfStudents = numberOfStudents;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	
	

}

Step 2:

  • Create a jsp page.
  • Create a form in the page which has three input fields and a submit button.
  • Enter the course title, code, number of students take the course in the input fields given and click on the submit button.

Listing 6: courseForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="#99CCFF">
<div align="center">
<form action="paramEg.jsp">
<h1>Course Details</h1>
Course title : <input type="text" name="title"/><br>
Course code : <input type="text" name="code"/><br>
Number of students : <input type="text" name="studentNumber"/><br>
<input type="submit" value="submit" />
</form>
</div>
</body>
</html>

Step 3:

  • Create a jsp page.
  • Set the parameters of the page using the attribute "PARAM".
  • Print the parameters using the <jsp:getProperty> to test the values set to the bean.

Listing 7: paramEg.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="#99CCFF">
<jsp:useBean id="course1" class="com.javaBeans.Course" />
<jsp:setProperty name="course1" property="title" param="title" />
<jsp:setProperty name="course1" property="code" param="code" />
<jsp:setProperty name="course1" property="numberOfStudents" param="studentNumber" />
<div align="center"><h2>
Here are the values set to the bean using the attribute 'param'
</h2>
<jsp:getProperty name="course1" property="title"/><br>
<jsp:getProperty name="course1" property="code"/><br>
<jsp:getProperty name="course1" property="numberOfStudents"/>
</div>
</body>
</html>
Result of the courseForm.jsp

Figure 3: Result of the courseForm.jsp

Redirected to the page paramEg.jsp page after entering details in courseForm.jsp and clicking on the submit button

Figure 4: Redirected to the page paramEg.jsp page after entering details in courseForm.jsp and clicking on the submit button. Values printed in the resulting page are coming from courseForm.jsp as a request parameters and set to the bean using PARAM attribute.

Java Bean scope in JSP:

We have seen using java beans in jsp page till now. According to the basic syntax , <jsp:useBean> loads and instantiates the bean object and this object to visible only to the page in which it is created.But in real time scenario, we might need an object to persist either for a whole session or per each user request etc.

This requirement is handled by the scope attribute of the standard action <jsp:useBean> .

Scope attribute gives the user a feasibility to change the visibility and accessibility of the object depending on the requirement.Like in java , variables has scope (local/global) , java beans in jsp also have the scope.

Let us look into detail about the scope concept:

Scope is an attribute of the jsp standard action <jsp:useBean> . When declaring the bean object itself we mention the scope of the object.

Scope attribute accepts the following four values:

  • Page
  • Request
  • Session
  • Application

At the time of the bean creation , the container creates a new reference of the object only if the scope is local. If the bean already exists , container checks to see if the new bean has the same id and scope as that of the existing bean. If both have the same id and scope values then the container uses the existing bean reference. Otherwise creates the new reference.

Let us look into detail about each scope:

This is the default scope. As you have seen in our previous examples , scope is not mentioned anywhere. In such scenarios where no scope value is mentioned, the default value “page” is assigned to the scope attribute.

This scope restricts the object’s visibility to the current processed page. i.e; the object is accessible to <jsp:getProperty> , <jsp:setProperty>, scriptlets or expressions coded in that particular page alone.

The object’s reference is diminished once the page is processed and is not accessible to any other JSP or servlets under any circumstances.

Request:

This scope refers to the next level objects visibility ie; the object can be accessed across the page with in the same request .

The objects reference is available to the JSP or servlet that is called by jsp forward or include or request dispatcher object.

The syntax of the request scope is as shown below :

<jsp:useBean id=”course” class=”com.javaBeans.Course” scope=”request” />

Session:

Session scope extends the object’s availability to all the JSP pages or servlets, but only to a single user until the session persists.

The object’s reference is available even though the user navigates through different pages .

But once the session is invalidated the object’s references are removed and are not available to the user.

<jsp:useBean id=”course” class=”com.javaBeans.Course” scope=”session” />

Application:

Assigning the value “application” to the scope attribute implies that the bean object is available to the whole application i.e; to all the JSP pages and servlets and also across multiple users unlike session scope which limits the object’s reference to a single user.

This scope should not be used until and unless it is really necessary according to the requirements, as any sensitive data might be visible to all other users.

For example, let us think of a bean object which holds the telephone number of the user has an application scope. Since the object’s reference is accessible throughout the application , whenever the bean is populated with the telephone number , the data is published to all the users , which is not permissible in real time scenario.

Hence one should be cautious while using the application scope.

<jsp:useBean id=”course” class=”com.javaBeans.Course” scope=”application” />

Conclusion

Above examples demonstrate using java beans in jsp . At the end of the section you have learnt what a java bean is , and how to work with beans in jsp such as getting the bean properties and setting the bean properties . Most importantly we learnt about the scope concept as it maintains a bean persistence either in a user session or across the application etc.



Have done masters in computer and have done various courses on java, PHP, android

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login