Sunday, May 3, 2015

JSP - Beans

How to create a bean, set bean values and access bean values

In this example, we are going to create a Shopping Item - bean and access it's values in a JSP page.
Beans allow to share data across multiple JSPs.

ShoppingItem.java - Bean


package com.beans;

// ShoppingItem - bean

public class ShoppingItem {

    private String itemId;
    private String desc;
    private double price;
   
    public String getItemId() {
        return itemId;
    }

    public void setItemId(String itemId) {
        this.itemId = itemId;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
   
}

 

setItem.jsp 

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Shopping Items</title>
</head>
<body>

<!-- Set bean values -->
    <jsp:useBean id="item1" class="com.beans.ShoppingItem" scope="session"></jsp:useBean>
    <jsp:setProperty property="itemId" name="item1" value="1000"/>
    <jsp:setProperty property="desc" name="item1" value="Samsung S6"/>
    <jsp:setProperty property="price" name="item1" value="700"/>
   
    <p>Bean properties has been set.</p>
   
</body>
</html>

 

getItem.jsp

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Shopping Items</title>
</head>
<body>

    <!-- Get bean values -->
    <jsp:useBean id="item1" class="com.beans.ShoppingItem" scope="session"></jsp:useBean>
    <p>Item ID : <%= item1.getItemId() %></p>
    <p>Item Description : <%= item1.getDesc() %></p>
    <p>Item Price : $<%= item1.getPrice() %></p>
   
   
</body>
</html> 

Notes:

  • The "id" property in the useBean jsp tag should be the same when you set the bean properties as well as when you retrieve the bean values.
  • First run the setItem.jsp file and then the viewItem.jsp file. If not the values in the viewItem.jsp will be null for string and 0.0 for double.

Tools Used:

  • Eclipse Kepler 

    Project Directory
    Output