Java.Servlet.What is a JavaBean?

A JavaBean is just a regular Java class that:

  1. Has a public no-argument constructor (so the server can create it easily).
  2. Has private fields (data) with public getter and setter methods.
  3. Implements Serializable interface (optional, but often recommended for distributed apps).

✅ It’s like a data holder: it stores information and allows you to get/set it cleanly.


🎯 Example of a JavaBean

package com.example;

public class User {
    private String name;
    private int age;

    // Public no-argument constructor
    public User() {}

    // Getter and Setter for name
    public String getName() {
        return name;
    }

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

    // Getter and Setter for age
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

name and age are private fields.

getName(), setName(), getAge(), setAge() are public access methods.

📜 How JavaBeans are used in JSP?

Using action tags, you can create a bean, set properties, and get properties without writing Java code manually.

Example JSP:

<jsp:useBean id="user" class="com.example.User" scope="session" />
<jsp:setProperty name="user" property="name" value="Stanley" />
<jsp:setProperty name="user" property="age" value="30" />

<p>Hello, <jsp:getProperty name="user" property="name" />!</p>
<p>You are <jsp:getProperty name="user" property="age" /> years old.</p>

What happens here:

  • useBean creates a new User object and stores it in the session.
  • setProperty sets the name and age.
  • getProperty reads them and outputs into the page.

Result:

Hello, Stanley!
You are 30 years old.

📢 Important points about JavaBeans:

  • They are not enterprise-level EJBs (Enterprise JavaBeans).
    ➔ JavaBeans are simple, lightweight classes for holding data.
  • JSPs use JavaBeans to bind form fields to backend objects easily.
  • JavaBeans help separate business logic (Java code) from presentation (JSP HTML).

🎯 In short:

When I said “beans” earlier, I meant simple Java objects (JavaBeans) that are easy to create, set, and read inside JSP using special action tags.

This entry was posted in Без рубрики. Bookmark the permalink.