How to use and create a Java Bean

A java bean is basically a class with getters and setters that is called into a JSP page.

The Java Bean: WelcomeBean.java

This java bean just sets and gets a welcome message.

package your.package;

public class JavaBean {
        public String welcomeMessage = "Hello there World from the Bean";

        public String getWelcomeMessage() {
                return this.welcomeMessage;
        }

        public void setWelcomeMessage(String msg) {
                if (msg != null) {
                        this.welcomeMessage = msg;
                }
        }
}

The JSP page that uses the java bean

The line that calls your java bean class is <jsp:useBean id="welcome" class="your.package.WelcomeBean" />. The id="welcome" part will be how you call your getters and setters. Such as welcome.setWelcomeMessage("The new welcome message.") and welcome.getWelcomeMessage().

<?xml version="1.0" encoding="ISO-8859-1" ?>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" session="true" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

<jsp:useBean id="welcome" class="your.package.WelcomeBean" />

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Java Bean Example</title>
</head>
<body>
<p>Getting welcome message from bean: <% out.print(welcome.getWelcomeMessage()); %></p>

<p>Setting welcome message with bean: <% welcome.setWelcomeMessage("The new welcome message."); out.print(welcome.getWelcomeMessage()); %></p>
</body>
</html>

Page Comments (Click to edit)






[Click to add or edit comments])

Please prepend comments below including a date

Design by N.Design Studio, adapted by solidGone.org (version 1.0.0)
Have a nice day.