Skip to contentSkip to navigationSkip to topbar
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

1
package com.twilio.phonetree.servlet.ivr;
2
3
import com.twilio.twiml.TwiMLException;
4
import com.twilio.twiml.VoiceResponse;
5
import com.twilio.twiml.voice.Gather;
6
import com.twilio.twiml.voice.Play;
7
8
import javax.servlet.http.HttpServlet;
9
import javax.servlet.http.HttpServletRequest;
10
import javax.servlet.http.HttpServletResponse;
11
import java.io.IOException;
12
13
public class WelcomeServlet extends HttpServlet {
14
15
@Override
16
protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
17
throws IOException {
18
String mp3file = "https://raw.githubusercontent.com/TwilioDevEd/"
19
+ "ivr-phone-tree-servlets/master/et-phone.mp3";
20
VoiceResponse response = new VoiceResponse.Builder()
21
.gather(new Gather.Builder()
22
.action("/menu/show")
23
.numDigits(1)
24
.build())
25
.play(new Play.Builder(mp3file)
26
.loop(3)
27
.build())
28
.build();
29
30
servletResponse.setContentType("text/xml");
31
try {
32
servletResponse.getWriter().write(response.toXml());
33
} catch (TwiMLException e) {
34
throw new RuntimeException(e);
35
}
36
}
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

1
package com.twilio.phonetree.servlet.ivr;
2
3
import com.twilio.twiml.TwiMLException;
4
import com.twilio.twiml.VoiceResponse;
5
import com.twilio.twiml.voice.Gather;
6
import com.twilio.twiml.voice.Play;
7
8
import javax.servlet.http.HttpServlet;
9
import javax.servlet.http.HttpServletRequest;
10
import javax.servlet.http.HttpServletResponse;
11
import java.io.IOException;
12
13
public class WelcomeServlet extends HttpServlet {
14
15
@Override
16
protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
17
throws IOException {
18
String mp3file = "https://raw.githubusercontent.com/TwilioDevEd/"
19
+ "ivr-phone-tree-servlets/master/et-phone.mp3";
20
VoiceResponse response = new VoiceResponse.Builder()
21
.gather(new Gather.Builder()
22
.action("/menu/show")
23
.numDigits(1)
24
.build())
25
.play(new Play.Builder(mp3file)
26
.loop(3)
27
.build())
28
.build();
29
30
servletResponse.setContentType("text/xml");
31
try {
32
servletResponse.getWriter().write(response.toXml());
33
} catch (TwiMLException e) {
34
throw new RuntimeException(e);
35
}
36
}
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

1
package com.twilio.phonetree.servlet.menu;
2
3
4
import com.twilio.twiml.TwiMLException;
5
import com.twilio.twiml.VoiceResponse;
6
import com.twilio.twiml.voice.Gather;
7
import com.twilio.twiml.voice.Hangup;
8
import com.twilio.twiml.voice.Say;
9
10
import javax.servlet.http.HttpServlet;
11
import javax.servlet.http.HttpServletRequest;
12
import javax.servlet.http.HttpServletResponse;
13
import java.io.IOException;
14
15
public class ShowServlet extends HttpServlet {
16
17
@Override
18
protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
19
throws IOException {
20
21
String selectedOption = servletRequest.getParameter("Digits");
22
23
VoiceResponse response;
24
switch (selectedOption) {
25
case "1":
26
response = getReturnInstructions();
27
break;
28
case "2":
29
response = getPlanets();
30
break;
31
default:
32
response = com.twilio.phonetree.servlet.common.Redirect.toMainMenu();
33
}
34
35
servletResponse.setContentType("text/xml");
36
try {
37
servletResponse.getWriter().write(response.toXml());
38
} catch (TwiMLException e) {
39
throw new RuntimeException(e);
40
}
41
}
42
43
private VoiceResponse getReturnInstructions() {
44
45
VoiceResponse response = new VoiceResponse.Builder()
46
.say(new Say.Builder(
47
"To get to your extraction point, get on your bike and go down "
48
+ "the street. Then Left down an alley. Avoid the police cars. Turn left "
49
+ "into an unfinished housing development. Fly over the roadblock. Go "
50
+ "passed the moon. Soon after you will see your mother ship.")
51
.voice(Say.Voice.POLLY_AMY)
52
.language(Say.Language.EN_GB)
53
.build())
54
.say(new Say.Builder(
55
"Thank you for calling the ET Phone Home Service - the "
56
+ "adventurous alien's first choice in intergalactic travel")
57
.build())
58
.hangup(new Hangup.Builder().build())
59
.build();
60
61
return response;
62
}
63
64
private VoiceResponse getPlanets() {
65
66
VoiceResponse response = new VoiceResponse.Builder()
67
.gather(new Gather.Builder()
68
.action("/commuter/connect")
69
.numDigits(1)
70
.build())
71
.say(new Say.Builder(
72
"To call the planet Broh doe As O G, press 2. To call the planet "
73
+ "DuhGo bah, press 3. To call an oober asteroid to your location"
74
+ ", press 4. To go back to the main menu, press the star key ")
75
.voice(Say.Voice.POLLY_AMY)
76
.language(Say.Language.EN_GB)
77
.loop(3)
78
.build()
79
).build();
80
81
return response;
82
}
83
}
84

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

1
package com.twilio.phonetree.servlet.commuter;
2
3
import com.twilio.phonetree.servlet.common.Redirect;
4
import com.twilio.twiml.voice.Dial;
5
import com.twilio.twiml.voice.Number;
6
import com.twilio.twiml.TwiMLException;
7
import com.twilio.twiml.VoiceResponse;
8
9
import javax.servlet.http.HttpServlet;
10
import javax.servlet.http.HttpServletRequest;
11
import javax.servlet.http.HttpServletResponse;
12
import java.io.IOException;
13
import java.util.HashMap;
14
import java.util.Map;
15
16
public class ConnectServlet extends HttpServlet {
17
18
@Override
19
protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
20
throws IOException {
21
22
String selectedOption = servletRequest.getParameter("Digits");
23
Map<String, String> optionPhones = new HashMap<>();
24
optionPhones.put("2", "+19295566487");
25
optionPhones.put("3", "+17262043675");
26
optionPhones.put("4", "+16513582243");
27
28
VoiceResponse twiMLResponse = optionPhones.containsKey(selectedOption)
29
? dial(optionPhones.get(selectedOption))
30
: Redirect.toMainMenu();
31
32
servletResponse.setContentType("text/xml");
33
try {
34
servletResponse.getWriter().write(twiMLResponse.toXml());
35
} catch (TwiMLException e) {
36
throw new RuntimeException(e);
37
}
38
}
39
40
private VoiceResponse dial(String phoneNumber) {
41
Number number = new Number.Builder(phoneNumber).build();
42
return new VoiceResponse.Builder()
43
.dial(new Dial.Builder().number(number).build())
44
.build();
45
}
46
}
47

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.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.