JavaBeans

Using beans makes working with JSPs easier for all levels of programmers.
Bean Scopes

As we have discussed in previous months, the servlet container loads only a single copy of every servlet into memory at a given time. It can get away with this because Java is multithreaded, allowing a particular servlet to be executing simultaneously for several HTTP requests. Since JSPs are actually servlets in disguise, they are also subject to issues of multithreading.

This raises the question of what happens to our JavaBeans: how many times are they loaded; what is their scope? If a JSP sets a property that happens to modify a class' fields, does this affect all of the other instances of the same bean?

The answer is: It depends. There are four different types of bean scopes, and the type of scope that you choose will profoundly affect the way your bean is used. Application scope means a single copy of the bean for all JSPs is running within the servlet container. Session scope is for a single user, from the time they enter the site to the time they exit. If a user opens two browser windows onto your system, they will have identical sessions. Request scope extends through the end of an HTTP request. This is useful if you want to set a bean's properties in one JSP, use the <jsp:forward/> tag to perform an internal redirect to a second JSP and then continue to use that same bean from the second JSP. Page scope is for a single JSP page. When the page exits, so does the scope.

By default, beans are placed in the session scope. You can change this by adding a scope parameter to the <jsp:useBean/>:

<jsp:useBean id="simple" scope="application"
 class="il.co.lerner.SimpleBean"/>

Once we have done the above, properties set by one JSP will be visible to other JSPs. Of course, because beans in the application and server scopes might be executed by more than one JSP simultaneously, they must be threadsafe. Consider the scopes in which your beans are meant to be used, and make them threadsafe as necessary. If a bean is not threadsafe, be sure to indicate as much in its documentation so that others will not mistakenly use it in the wrong way.

Web Log

Last month, we continued our simple investigations of web logs with a JSP that directly accessed a relational database to get the latest contents of a web log. While such a JSP is certainly legal, it looks awkward, is difficult to debug and fails to separate code from logic as elegantly as we might have hoped.

By putting the database logic into a JavaBean, we can achieve several of our goals: the code is reusable, available even to nonprogrammers and allows us to change the source of information or the application logic without rewriting our JSP. Listing 5 (available at ftp.linuxjournal.com/pub/lj/listings/issue86) contains the source code for our bean, which I have made threadsafe (using the “synchronized” keyword within the getBlog method) so we can create a single instance of application scope. This JavaBean connects to the web log database and retrieves the latest information. Listing 6 contains a small JSP that uses this JavaBean to display the web log.

Listing 6. viewblog.jsp

There really isn't anything special about the bean in Listing 5, but it does bring together a number of things that we have been discussing in the last few months. We now have a way for nonprogrammers to access information in our web log without having to write a single line of code on their own! Using a few simple JSP tags, we can place our current blog contents in an HTML page quickly and easily.

Conclusion

JavaBeans are a wonderful way in which to reduce the amount of code we put in our JSPs, while making it easier to use. However, complex JSPs will still contain some code, such as when they have to iterate through loops or work with complex data.

Next month, we will see how we can write our own tags similar to the jsp: tags we saw this month, using JSP's custom actions facility. Therefore, we can create our own new tags, associating them with any code we wish. In this way, JSPs allow us to create our own new formatting language, as well as use the tags that have been provided.

Resources

Reuven M. Lerner owns and manages a small consulting firm specializing in web and internet technologies. As you read this, he should be (finally) finishing Core Perl, to be published by Prentice-Hall later this year. You can reach him at reuven@lerner.co.il, or at the ATF home page, http://www.lerner.co.il/atf/.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

help !! Struck in java bean

Anonymous's picture

hi all
lets starts with my problem!!!!
i have created a javabean which stores the password and username.I have created a bean so that if an unauthenticated user types the URL of any other pages before going to login first he will be greeted with the message to login first.
But i m not be able to do this.
plz help
i have admin.jsp thats asks for username and password.then it is redirected to welcome.jsp.
but if an unauthenicated user types the url of welcome.jsp he must get the msg to login first.
also tell me if i m right in creating a bean for storing username and password.
Thanks

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState