O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

20.5. Accessing Email from a Servlet Using a JavaBean

Problem

You want to use a JavaBean or helper class to access and display email messages.

Solution

Add the handleMessages( ) and displayMessage( ) methods from Example 20-4 to the JavaBean class defined in Example 20-2. Then use the JavaBean from a servlet's doGet( ) or doPost( ) method.

Discussion

When we last encountered the EmailBean in Example 20-2 it contained a sendMessage( ) method, along with several property "setter" methods (such as setSmtpHost(String host)). If you add the handleMessages( ) and displayMessage( ) methods from Example 20-4 to this same class, you can use the JavaBean to both send and access email.

Note

This code in handleMessages( ) from Example 20-4 needs to be changed to include the EmailBean class name:

//static reference to a constant value
if (! check(popAddr))
    popAddr = EmailBean.DEFAULT_SERVER;

However, the EmailBean class will have grown quite large as a result of adding the two methods, so you might create two JavaBeans—one for sending mail and another for accessing it. Example 20-5 creates and uses an instance of a special email JavaBean. You must store the bean class in the WEB-INF/classes directory or in a JAR file in WEB-INF/lib.

Tip

Example 20-6 also shows a JavaBean that defines handleMessages( ) and displayMessage( ) for dealing with email attachments.

Example 20-5. A servlet uses a JavaBean to access email messages

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required