Instant Lead Alerts with Java and Servlets

You probably already have landing pages or product detail views which you're using to generate some excellent leads for your business.  Would you like to let the sales team know when you've got a new qualified lead?

In this tutorial we'll use Twilio Programmable SMS with Java and Servlets to send a message when a new lead is found.

Lead Alerts Flow

In this example, we'll be implementing instant lead alerts for a fictional real estate agency.

We'll create a landing page for a new house on the market and a form for web surfers to request additional information.  The form will trigger notifications to our agents in the field, who can follow up and hopefully close the deal.

Learn how Porch uses Twilio SMS to send home contractors instant alerts when they are selected for a new project.

Let's see how it works!  Click the button below to begin.

Populate Landing Page Data

To display a landing page for the house, we need to have some information to show the user. For demonstration purposes, we've hard-coded the information we'd like to show.

Loading Code Samples...
Language
package com.twilio.leadalerts;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HomeServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setAttribute("houseTitle", "555 Sunnybrook Lane");
        request.setAttribute("housePrice", "$349,999");
        request.setAttribute("houseDescription",
                "You and your family will love this charming home. " +
                "Featuring granite appliances, stainless steel windows, and " +
                "high efficiency dual mud rooms, this joint is loaded to the max. " +
                "Motivated sellers have priced for a quick sale, act now!");

        request.getRequestDispatcher("home.jsp").forward(request, response);
    }
}
src/main/java/com/twilio/leadalerts/HomeServlet.java
GET request handler that returns data for a listing

src/main/java/com/twilio/leadalerts/HomeServlet.java

Now we have a method to serve the house data.

Next up, let's see how to use this data to render the Landing Page.

Render the Landing Page

In our landing page we'll insert the data about the house. We'll also add a sidebar form for the user to enter in their contact information and request additional information.

Loading Code Samples...
Language
<%@ page pageEncoding="UTF-8" %>
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lead Alerts</title>

    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet">
    <link href="css/site.css" rel="stylesheet">
</head>
<body>
    <div id="main" class="container">
        <core:if test="${not empty success}">
            <div class="alert alert-success" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
                ${success}
            </div>
        </core:if>
        <core:if test="${not empty error}">
            <div class="alert alert-danger" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
                ${error}
            </div>
        </core:if>
        <div class="row">
            <div class="col-sm-8">
                <h1>${houseTitle}</h1>
                <h3>${housePrice}</h3>
                <img src="images/house.jpg" alt="House" />
                <p>${houseDescription}</p>
            </div>
            <div class="col-sm-2 demo">
                <h4>Talk To An Agent</h4>
                <p>
                    A trained real estate professional is standing by to answer any
                    questions you might have about this property. Fill out the form below
                    with your contact information, and an agent will reach out soon.
                </p>
                <form action="/notifications" method="POST">
                    <input type="hidden" name="houseTitle" value="${houseTitle}" />
                    <div class="form-group">
                        <label for="name">Your Name</label>
                        <input type="text" id="name" name="name" class="form-control" placeholder="John Appleseed" />
                    </div>
                    <div class="form-group">
                        <label for="phone">Your Phone Number</label>
                        <input type="text" id="phone" name="phone" class="form-control" placeholder="+16512229988" />
                    </div>
                    <div class="form-group">
                        <label for="message">How can we help?</label>
                        <input type="text" id="message" name="message" class="form-control" />
                    </div>
                    <button type="submit" class="btn btn-primary">Request Info</button>
                </form>
            </div>
        </div>
    </div>
    <footer class="container">
        Made with <i class="fa fa-heart"></i> by your pals <a href="http://www.twilio.com">@twilio</a>.
    </footer>
    <script src="//code.jquery.com/jquery-2.1.4.js"></script>
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
src/main/webapp/home.jsp
Template for the landing page

src/main/webapp/home.jsp

Our landing page template is ready (and looks great).

Now let's see how to initialize the Twilio REST Client to send messages.

Create a Twilio REST API Client

Here we create a helper class with an authenticated Twilio REST API client that we can use anytime we need to send a text message.

We initialize it with our Twilio Account Credentials stored as environment variables.  You can find the Auth Token and Account SID in the console:

console credentials

Loading Code Samples...
Language
package com.twilio.leadalerts.lib;

import com.twilio.http.TwilioRestClient;
import com.twilio.leadalerts.lib.config.Credentials;
import com.twilio.leadalerts.lib.config.PhoneNumbers;
import com.twilio.rest.api.v2010.account.MessageCreator;
import com.twilio.type.PhoneNumber;

@SuppressWarnings("unused")
public class MessageSender {
    private final TwilioRestClient client;

    public MessageSender() {
        client = new TwilioRestClient.Builder(
                Credentials.getTwilioAccountSid(),
                Credentials.getTwilioAuthToken()).build();
    }

    public MessageSender(TwilioRestClient client) {
        this.client = client;
    }

    public void send(String message) {
        new MessageCreator(
                new PhoneNumber(PhoneNumbers.getAgentPhoneNumber()),
                new PhoneNumber(PhoneNumbers.getTwilioPhoneNumber()),
                message
        ).create(client);
    }

}
src/main/java/com/twilio/leadalerts/lib/MessageSender.java
Twilio REST Client wrapper to simplify sending messages

src/main/java/com/twilio/leadalerts/lib/MessageSender.java

Our Twilio Client is now ready to send messages! Next up, let's see how to handle incoming leads.

Handle Incoming POST Requests

This code handles the HTTP POST request from our landing page when a browser expresses interest through our form.

It uses our MessageSender class to send an SMS message to the real estate agent's phone number, which is stored as an environment variable. We include the lead's name, phone number, and inquiry directly in the body of the text message we send to the agent.

Now the agent has all the information he or she needs to quickly follow up with the new lead.

Loading Code Samples...
Language
package com.twilio.leadalerts;

import com.twilio.leadalerts.lib.MessageSender;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class NotificationsServlet extends HttpServlet {

    private final MessageSender messageSender;

    @SuppressWarnings("unused")
    public NotificationsServlet() {
        this(new MessageSender());
    }

    public NotificationsServlet(MessageSender messageSender) {
        this.messageSender = messageSender;
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String houseTitle = request.getParameter("houseTitle");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String message = request.getParameter("message");

        String formattedMessage = formatMessage(houseTitle, name, phone, message);
        try {
            messageSender.send(formattedMessage);
            request.setAttribute("success", "Thanks! An agent will be contacting you shortly.");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "Oops! There was an error. Please try again.");
        }

        request.getRequestDispatcher("home.jsp").forward(request, response);
    }


    private String formatMessage(String houseTitle, String name, String phone, String message) {
        return String.format("New lead received for %s. Call %s at %s. Message: %s",
                houseTitle, name, phone, message);
    }
}
src/main/java/com/twilio/leadalerts/NotificationsServlet.java
Handle incoming sales leads and notify an agent

src/main/java/com/twilio/leadalerts/NotificationsServlet.java

That's a wrap! We've just implemented an application to instantly route leads to salespeople using text messages.

On the next page, we'll point out a few other useful features that are perfect for your application.

Where to Next?

Java and Twilio go oh so well together.  We'll prove it; here are a couple of our favorite Java tutorials:

Click-To-Call

Click-to-call enables your company to convert web traffic into phone calls with the click of a button.

IVR: Phone Tree

Easily route callers to the right people and information with an IVR (interactive voice response) system.

Did this help?

Thanks for checking out this tutorial... tweet @twilio to let us know what you're building!

Agustin Camino
Paul Kamp
Andrew Baker
Jose Oliveros

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

1 / 1
Loading Code Samples...
package com.twilio.leadalerts;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HomeServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setAttribute("houseTitle", "555 Sunnybrook Lane");
        request.setAttribute("housePrice", "$349,999");
        request.setAttribute("houseDescription",
                "You and your family will love this charming home. " +
                "Featuring granite appliances, stainless steel windows, and " +
                "high efficiency dual mud rooms, this joint is loaded to the max. " +
                "Motivated sellers have priced for a quick sale, act now!");

        request.getRequestDispatcher("home.jsp").forward(request, response);
    }
}
<%@ page pageEncoding="UTF-8" %>
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lead Alerts</title>

    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet">
    <link href="css/site.css" rel="stylesheet">
</head>
<body>
    <div id="main" class="container">
        <core:if test="${not empty success}">
            <div class="alert alert-success" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
                ${success}
            </div>
        </core:if>
        <core:if test="${not empty error}">
            <div class="alert alert-danger" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
                ${error}
            </div>
        </core:if>
        <div class="row">
            <div class="col-sm-8">
                <h1>${houseTitle}</h1>
                <h3>${housePrice}</h3>
                <img src="images/house.jpg" alt="House" />
                <p>${houseDescription}</p>
            </div>
            <div class="col-sm-2 demo">
                <h4>Talk To An Agent</h4>
                <p>
                    A trained real estate professional is standing by to answer any
                    questions you might have about this property. Fill out the form below
                    with your contact information, and an agent will reach out soon.
                </p>
                <form action="/notifications" method="POST">
                    <input type="hidden" name="houseTitle" value="${houseTitle}" />
                    <div class="form-group">
                        <label for="name">Your Name</label>
                        <input type="text" id="name" name="name" class="form-control" placeholder="John Appleseed" />
                    </div>
                    <div class="form-group">
                        <label for="phone">Your Phone Number</label>
                        <input type="text" id="phone" name="phone" class="form-control" placeholder="+16512229988" />
                    </div>
                    <div class="form-group">
                        <label for="message">How can we help?</label>
                        <input type="text" id="message" name="message" class="form-control" />
                    </div>
                    <button type="submit" class="btn btn-primary">Request Info</button>
                </form>
            </div>
        </div>
    </div>
    <footer class="container">
        Made with <i class="fa fa-heart"></i> by your pals <a href="http://www.twilio.com">@twilio</a>.
    </footer>
    <script src="//code.jquery.com/jquery-2.1.4.js"></script>
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
package com.twilio.leadalerts.lib;

import com.twilio.http.TwilioRestClient;
import com.twilio.leadalerts.lib.config.Credentials;
import com.twilio.leadalerts.lib.config.PhoneNumbers;
import com.twilio.rest.api.v2010.account.MessageCreator;
import com.twilio.type.PhoneNumber;

@SuppressWarnings("unused")
public class MessageSender {
    private final TwilioRestClient client;

    public MessageSender() {
        client = new TwilioRestClient.Builder(
                Credentials.getTwilioAccountSid(),
                Credentials.getTwilioAuthToken()).build();
    }

    public MessageSender(TwilioRestClient client) {
        this.client = client;
    }

    public void send(String message) {
        new MessageCreator(
                new PhoneNumber(PhoneNumbers.getAgentPhoneNumber()),
                new PhoneNumber(PhoneNumbers.getTwilioPhoneNumber()),
                message
        ).create(client);
    }

}
package com.twilio.leadalerts;

import com.twilio.leadalerts.lib.MessageSender;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class NotificationsServlet extends HttpServlet {

    private final MessageSender messageSender;

    @SuppressWarnings("unused")
    public NotificationsServlet() {
        this(new MessageSender());
    }

    public NotificationsServlet(MessageSender messageSender) {
        this.messageSender = messageSender;
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String houseTitle = request.getParameter("houseTitle");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String message = request.getParameter("message");

        String formattedMessage = formatMessage(houseTitle, name, phone, message);
        try {
            messageSender.send(formattedMessage);
            request.setAttribute("success", "Thanks! An agent will be contacting you shortly.");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "Oops! There was an error. Please try again.");
        }

        request.getRequestDispatcher("home.jsp").forward(request, response);
    }


    private String formatMessage(String houseTitle, String name, String phone, String message) {
        return String.format("New lead received for %s. Call %s at %s. Message: %s",
                houseTitle, name, phone, message);
    }
}