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.3. Sending Email from a Servlet Using a JavaBean

Problem

You want to use a JavaBean or helper class to send email from a servlet.

Solution

Develop a Java class that implements a sendMessage( ) method (just a name I gave it) to construct an email and send it. Store the new class in the WEB-INF/classes folder of the web application, including the class's package-related folders.

Discussion

You may choose to separate the responsibilities of handling HTTP requests and managing email by encapsulating these tasks in separate classes. A JavaBean that provides the essential function of sending email fits the bill here.

Tip

Recipe 20.5 and Recipe 20.6 show JavaBeans that are used to access email and handle attachments. A bean that does everything email-related grows fairly large in size, so developers must make a design decision about whether to separate these tasks into different JavaBeans (or utility classes) that can be used from servlets.

Create the bean and store it in the WEB-INF/classes folder. Example 20-3 shows the doGet( ) method of an HttpServlet using a JavaBean to send an email. Example 20-2 shows the bean class itself. The difference between the sendMessage( ) method of Example 20-1 and the one in Example 20-2 is in the way the bean receives the various email parts, such as the recipient's email address. The bean stores these parts as properties and uses setter methods to provide the property values.

Tip

On the other hand, Example 20-1 uses request parameters and method arguments ...

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