简体   繁体   中英

Place the business logic in Java Beans?

I was reading this page and I found the following statement:

MVC in Java Server Pages

Now that we have a convenient architucture to separate the view, how can we leverage that? Java Server Pages (JSP) becomes more interesting because the HTML content can be separated from the Java business objects. JSP can also make use of Java Beans. The business logic could be placed inside Java Beans. If the design is architected correctly, a Web Designer could work with HTML on the JSP site without interfering with the Java developer.

Interestingly in my textbook I pulled the following quote:

In the MVC architecture... the original request is always handled by a servlet. The servlet invokes the business logic and data access code and creates beans to represent the results (that's the model). Then, the servlet decides which Java Server Page is appropriate to present those particular results and forwards the request there (the JSP is the view). The servlet decides what business logic code applies and which JSP should present the results (the servlet is the controller).

The two statements seem slightly contradicting. What is the best way to use beans: should we place business logic in them or should we only place results in them? Are there ways in which beans are inadequate for representing a model?

It's also pretty common for business logic to be placed in classes with a suffix of Manager. Although some people put business logic on the data object bean itself I find it best when methods on the data object only do simple functions that do not rely on any external dependencies. All the rest of the business logic I place in a Manager bean that is capable of using multiple data object javabeans and other external dependencies to follow the business logic. So for example an AccountBean would contain the account fields and maybe a few simple methods that use those fields to compute and return a value, or format a field. All the business logic would be in a Manager, possibly an AccountManagerBean.

The second statement is basically telling about two javabeans: one for business logic and other for the model. So, yes the business logic can still be placed in javabeans. The javabean for the business logic can encapsulate the javabean for model as its property.

public class User {
    private Long id;
    private String name;
    // ...
}

public class UserManager {
    private User user;
    // ...

    public void login() {
        // ...
    }

    public void logout() {
        // ...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM