Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
734 views
in Technique[技术] by (71.8m points)

java - What's the point of beans?

I've bean doing some JSP tutorials and I don't understand what the point of a bean class is. All it is, is get and set methods. why do we use them?

public class UserData {

String username;
String email;
int age;

public void setUsername( String value )
{
    username = value;
}

public void setEmail( String value )
{
    email = value;
}

public void setAge( int value )
{
    age = value;
}

public String getUsername() { return username; }

public String getEmail() { return email; }

public int getAge() { return age; }

}

and the jsp is

<jsp:useBean id="user" class="user.UserData" scope="session"/> 
<HTML>
<BODY>
You entered<BR>
Name: <%= user.getUsername() %><BR>
Email: <%= user.getEmail() %><BR>
Age: <%= user.getAge() %><BR>
</BODY>
</HTML>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. A Bean obtains all the benefits of Java's "write-once, run-anywhere" paradigm. The properties, events, and methods of a Bean that are exposed to an application builder tool can be controlled.

  2. A Bean may be designed to operate correctly in different locales, which makes it useful in global markets.

  3. Auxiliary software can be provided to help a person configure a Bean. This software is only needed when the design-time parameters for that component are being set. It does not need to be included in the run-time environment. The configuration settings of a Bean can be saved in persistent storage and restored at a later time.

  4. A Bean may register to receive events from other objects and can generate events that are sent to other objects.

The use of scriptlets (those <% %> things) is indeed highly discouraged since the birth of taglibs (like JSTL) and EL (Expression Language, those ${} things) over a decade ago. The major disadvantages of scriptlets are:

  1. Reusability: you can't reuse scriptlets.

  2. Replaceability: you can't make scriptlets abstract.

  3. OO-ability: you can't make use of inheritance/composition.

  4. Debuggability: if scriptlet throws an exception halfway, all you get is a blank page.

  5. Testability: scriptlets are not unit-testable.

  6. Maintainability: per saldo more time is needed to maintain mingled/cluttered/duplicated code logic.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...