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

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix