Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

IVR: Phone Tree with Java and Servlets


ET Phone Home: IVR Java & Servlets Example.

This Servlets(link takes you to an external page) sample application is modeled after a typical call center experience, but with more Reese's Pieces(link takes you to an external page).

Stranded aliens can call a phone number and receive instructions on how to get out of earth safely, or call their home planet(link takes you to an external page) directly. In this tutorial, we'll show you the key bits of code to make this work.

To run this sample app yourself, download the code and follow the instructions on GitHub(link takes you to an external page).

Read how Livestream(link takes you to an external page) and others(link takes you to an external page) built phone trees on IVR with Twilio. Find examples for many web frameworks and languages on our IVR application page.


Answering the Phone Call

answering-the-phone-call page anchor

To initiate the phone tree, we need to configure one of our Twilio numbers to send our web application an HTTP request when we get an incoming call.

Click on one of your numbers and configure the Voice URL to point to our app. In our code the route will be /ivr/welcome.

IVR Webhook Configuration.

If you don't already have a server configured to use as your webhook, ngrok(link takes you to an external page) is a great tool for testing webhooks locally.

With our Twilio number configured, we are prepared to respond to the Twilio request.


Respond to the Twilio request with TwiML

respond-to-the-twilio-request-with-twiml page anchor

Our Twilio number is now configured to send HTTP requests to this controller action on any incoming voice calls. Our app responds with TwiML to tell Twilio what to do in response to the message.

In this case we tell Twilio to Gather the input from the caller and Play a welcome message.

Respond with TwiML to gather an option from the caller

respond-with-twiml-to-gather-an-option-from-the-caller page anchor

src/main/java/com/twilio/phonetree/servlet/ivr/WelcomeServlet.java


_37
package com.twilio.phonetree.servlet.ivr;
_37
_37
import com.twilio.twiml.TwiMLException;
_37
import com.twilio.twiml.VoiceResponse;
_37
import com.twilio.twiml.voice.Gather;
_37
import com.twilio.twiml.voice.Play;
_37
_37
import javax.servlet.http.HttpServlet;
_37
import javax.servlet.http.HttpServletRequest;
_37
import javax.servlet.http.HttpServletResponse;
_37
import java.io.IOException;
_37
_37
public class WelcomeServlet extends HttpServlet {
_37
_37
@Override
_37
protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
_37
throws IOException {
_37
String mp3file = "https://raw.githubusercontent.com/TwilioDevEd/"
_37
+ "ivr-phone-tree-servlets/master/et-phone.mp3";
_37
VoiceResponse response = new VoiceResponse.Builder()
_37
.gather(new Gather.Builder()
_37
.action("/menu/show")
_37
.numDigits(1)
_37
.build())
_37
.play(new Play.Builder(mp3file)
_37
.loop(3)
_37
.build())
_37
.build();
_37
_37
servletResponse.setContentType("text/xml");
_37
try {
_37
servletResponse.getWriter().write(response.toXml());
_37
} catch (TwiMLException e) {
_37
throw new RuntimeException(e);
_37
}
_37
}
_37
}

After playing the audio and retrieving the caller's input, Twilio will send this input to our application.


Where to send the caller's input

where-to-send-the-callers-input page anchor

The gather's action parameter takes an absolute or relative URL as a value. In our case, this is the /menu/show route.

When the caller has finished entering digits, Twilio will make a GET or POST request to this URL that includes a Digits parameter with the number our caller chose.

After making this request, Twilio will continue the current call using the TwiML received in your response. Any TwiML verbs occurring after a <Gather> are unreachable, unless the caller enters no digits.

Send caller input to the intended route

send-caller-input-to-the-intended-route page anchor

src/main/java/com/twilio/phonetree/servlet/ivr/WelcomeServlet.java


_37
package com.twilio.phonetree.servlet.ivr;
_37
_37
import com.twilio.twiml.TwiMLException;
_37
import com.twilio.twiml.VoiceResponse;
_37
import com.twilio.twiml.voice.Gather;
_37
import com.twilio.twiml.voice.Play;
_37
_37
import javax.servlet.http.HttpServlet;
_37
import javax.servlet.http.HttpServletRequest;
_37
import javax.servlet.http.HttpServletResponse;
_37
import java.io.IOException;
_37
_37
public class WelcomeServlet extends HttpServlet {
_37
_37
@Override
_37
protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
_37
throws IOException {
_37
String mp3file = "https://raw.githubusercontent.com/TwilioDevEd/"
_37
+ "ivr-phone-tree-servlets/master/et-phone.mp3";
_37
VoiceResponse response = new VoiceResponse.Builder()
_37
.gather(new Gather.Builder()
_37
.action("/menu/show")
_37
.numDigits(1)
_37
.build())
_37
.play(new Play.Builder(mp3file)
_37
.loop(3)
_37
.build())
_37
.build();
_37
_37
servletResponse.setContentType("text/xml");
_37
try {
_37
servletResponse.getWriter().write(response.toXml());
_37
} catch (TwiMLException e) {
_37
throw new RuntimeException(e);
_37
}
_37
}
_37
}

Now that we have told Twilio where to send the caller's input, we can look at how to process that input.


The Main Menu: Process the caller's selection

the-main-menu-process-the-callers-selection page anchor

If our caller chooses '1' for directions, we use the getReturnInstructions helper method to respond with TwiML that will Say directions to our caller's extraction point.

If the caller chooses '2' to call their home planet, we need to gather more input from them. We'll cover this in the next step.

If the caller enters anything else, we respond with a TwiML Redirect to the main menu.


The Planet Directory: Collect more input from the caller

the-planet-directory-collect-more-input-from-the-caller page anchor

If our callers choose to call their home planet, we will read them the planet directory. This is similar to a typical "company directory" feature of most IVRs.

In our TwiML response we again use a Gather verb to collect our caller's input. This time, the action verb points to the planets route, which will switch our response based on what the caller chooses.

Collect more input from the caller via the Planet Directory

collect-more-input-from-the-caller-via-the-planet-directory page anchor

src/main/java/com/twilio/phonetree/servlet/menu/ShowServlet.java


_83
package com.twilio.phonetree.servlet.menu;
_83
_83
_83
import com.twilio.twiml.TwiMLException;
_83
import com.twilio.twiml.VoiceResponse;
_83
import com.twilio.twiml.voice.Gather;
_83
import com.twilio.twiml.voice.Hangup;
_83
import com.twilio.twiml.voice.Say;
_83
_83
import javax.servlet.http.HttpServlet;
_83
import javax.servlet.http.HttpServletRequest;
_83
import javax.servlet.http.HttpServletResponse;
_83
import java.io.IOException;
_83
_83
public class ShowServlet extends HttpServlet {
_83
_83
@Override
_83
protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
_83
throws IOException {
_83
_83
String selectedOption = servletRequest.getParameter("Digits");
_83
_83
VoiceResponse response;
_83
switch (selectedOption) {
_83
case "1":
_83
response = getReturnInstructions();
_83
break;
_83
case "2":
_83
response = getPlanets();
_83
break;
_83
default:
_83
response = com.twilio.phonetree.servlet.common.Redirect.toMainMenu();
_83
}
_83
_83
servletResponse.setContentType("text/xml");
_83
try {
_83
servletResponse.getWriter().write(response.toXml());
_83
} catch (TwiMLException e) {
_83
throw new RuntimeException(e);
_83
}
_83
}
_83
_83
private VoiceResponse getReturnInstructions() {
_83
_83
VoiceResponse response = new VoiceResponse.Builder()
_83
.say(new Say.Builder(
_83
"To get to your extraction point, get on your bike and go down "
_83
+ "the street. Then Left down an alley. Avoid the police cars. Turn left "
_83
+ "into an unfinished housing development. Fly over the roadblock. Go "
_83
+ "passed the moon. Soon after you will see your mother ship.")
_83
.voice(Say.Voice.POLLY_AMY)
_83
.language(Say.Language.EN_GB)
_83
.build())
_83
.say(new Say.Builder(
_83
"Thank you for calling the ET Phone Home Service - the "
_83
+ "adventurous alien's first choice in intergalactic travel")
_83
.build())
_83
.hangup(new Hangup.Builder().build())
_83
.build();
_83
_83
return response;
_83
}
_83
_83
private VoiceResponse getPlanets() {
_83
_83
VoiceResponse response = new VoiceResponse.Builder()
_83
.gather(new Gather.Builder()
_83
.action("/commuter/connect")
_83
.numDigits(1)
_83
.build())
_83
.say(new Say.Builder(
_83
"To call the planet Broh doe As O G, press 2. To call the planet "
_83
+ "DuhGo bah, press 3. To call an oober asteroid to your location"
_83
+ ", press 4. To go back to the main menu, press the star key ")
_83
.voice(Say.Voice.POLLY_AMY)
_83
.language(Say.Language.EN_GB)
_83
.loop(3)
_83
.build()
_83
).build();
_83
_83
return response;
_83
}
_83
}

Again we show some options to the caller and instruct Twilio to collect the caller's choice.


The Planet Directory: Connect the caller to another number

the-planet-directory-connect-the-caller-to-another-number page anchor

In this servlet, we grab the caller's selection from the request and store it in a variable called selectedOption. We then use a Dial verb with the appropriate phone number to connect our caller to the correct home planet.

The current numbers are hard coded, but they could also be read from a database or from a file.

Connect to another number based on caller input

connect-to-another-number-based-on-caller-input page anchor

src/main/java/com/twilio/phonetree/servlet/commuter/ConnectServlet.java


_46
package com.twilio.phonetree.servlet.commuter;
_46
_46
import com.twilio.phonetree.servlet.common.Redirect;
_46
import com.twilio.twiml.voice.Dial;
_46
import com.twilio.twiml.voice.Number;
_46
import com.twilio.twiml.TwiMLException;
_46
import com.twilio.twiml.VoiceResponse;
_46
_46
import javax.servlet.http.HttpServlet;
_46
import javax.servlet.http.HttpServletRequest;
_46
import javax.servlet.http.HttpServletResponse;
_46
import java.io.IOException;
_46
import java.util.HashMap;
_46
import java.util.Map;
_46
_46
public class ConnectServlet extends HttpServlet {
_46
_46
@Override
_46
protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
_46
throws IOException {
_46
_46
String selectedOption = servletRequest.getParameter("Digits");
_46
Map<String, String> optionPhones = new HashMap<>();
_46
optionPhones.put("2", "+19295566487");
_46
optionPhones.put("3", "+17262043675");
_46
optionPhones.put("4", "+16513582243");
_46
_46
VoiceResponse twiMLResponse = optionPhones.containsKey(selectedOption)
_46
? dial(optionPhones.get(selectedOption))
_46
: Redirect.toMainMenu();
_46
_46
servletResponse.setContentType("text/xml");
_46
try {
_46
servletResponse.getWriter().write(twiMLResponse.toXml());
_46
} catch (TwiMLException e) {
_46
throw new RuntimeException(e);
_46
}
_46
}
_46
_46
private VoiceResponse dial(String phoneNumber) {
_46
Number number = new Number.Builder(phoneNumber).build();
_46
return new VoiceResponse.Builder()
_46
.dial(new Dial.Builder().number(number).build())
_46
.build();
_46
}
_46
}

That's it! We've just implemented an IVR phone tree that will delight and serve your customers.


If you're a Java developer working with Twilio, you might enjoy these other tutorials:

Automated Survey(link takes you to an external page) (Spark)

Instantly collect structured data from your users with a survey conducted over a voice call or SMS text messages.

Click-To-Call (Servlets)

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

Did this help?

did-this-help page anchor

Thanks for checking out this tutorial! If you have any feedback to share with us, we'd love to hear it. Connect with us on Twitter(link takes you to an external page) and let us know what you build!


Rate this page: