Using Java Beans in JSP

Java bean is a Plain Old Java Object (POJO) having few attributes and getter and setter methods in it. These POJOs can be used in JSPs to send data to the server. It reduces the amount of Java code that exists in a JSP. Also the JSP will contain the presentation details only. Data handling is moved to the Java bean in this approach. This can be achieved using following simple steps.

Let us take an example, to display customer name on customer jsp using Customer Java bean. This is how the Java bean will be.

com.myorg.jsptutorial.Customer.java

package com.myorg.jsptutorial;

public class Customer {

	private String name = "Java Bean Example";

	public String getName() {
		return name;
	}

	public void setName(String aName) {
		this.name = aName;
	}

}

The jsp page using this Java bean is -

<html>

<head>

<title>Customer Java Bean Example</title>

</head>

<jsp:useBean id="customer" scope="page" class="com.myorg.jsptutorial.Customer"></jsp:useBean>

<body>

  <h1>Name is: <jsp:getProperty name="customer" property="name"/></h1>

</body>

</html>

In this Jsp, we are using <jsp:useBean> tag.  Here, getProperty tag will call getName method on bean and retrieve the default value. This value will be displayed in the JSP. Finally the JSP will be presented like this.

Using Java Bean

<<Previous   Home   Next>>

  • Share/Bookmark
JEE, Jsp, Tech Notes

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Leave Comment

(required)

(required)