IVR: Phone Tree with Java and Servlets

ET Phone Home

This Servlets sample application is modeled after a typical call center experience, but with more Reese's Pieces.

Stranded aliens can call a phone number and receive instructions on how to get out of earth safely, or call their home planet 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.

Read how Livestream used Twilio to build custom call routing logic and IVR messages.

Answering the Phone Call

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 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

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.

Loading Code Samples...
Language
package com.twilio.phonetree.servlet.ivr;

import com.twilio.twiml.Gather;
import com.twilio.twiml.Play;
import com.twilio.twiml.TwiMLException;
import com.twilio.twiml.VoiceResponse;

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

public class WelcomeServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
            throws IOException {
        VoiceResponse response = new VoiceResponse.Builder()
                .gather(new Gather.Builder()
                        .action("/menu/show")
                        .numDigits(1)
                        .build())
                .play(new Play.Builder("http://howtodocs.s3.amazonaws.com/et-phone.mp3")
                        .loop(3)
                        .build())
                .build();

        servletResponse.setContentType("text/xml");
        try {
            servletResponse.getWriter().write(response.toXml());
        } catch (TwiMLException e) {
            throw new RuntimeException(e);
        }
    }
}
src/main/java/com/twilio/phonetree/servlet/ivr/WelcomeServlet.java
Respond with TwiML to gather an option from the caller

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

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

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.

Loading Code Samples...
Language
package com.twilio.phonetree.servlet.ivr;

import com.twilio.twiml.Gather;
import com.twilio.twiml.Play;
import com.twilio.twiml.TwiMLException;
import com.twilio.twiml.VoiceResponse;

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

public class WelcomeServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
            throws IOException {
        VoiceResponse response = new VoiceResponse.Builder()
                .gather(new Gather.Builder()
                        .action("/menu/show")
                        .numDigits(1)
                        .build())
                .play(new Play.Builder("http://howtodocs.s3.amazonaws.com/et-phone.mp3")
                        .loop(3)
                        .build())
                .build();

        servletResponse.setContentType("text/xml");
        try {
            servletResponse.getWriter().write(response.toXml());
        } catch (TwiMLException e) {
            throw new RuntimeException(e);
        }
    }
}
src/main/java/com/twilio/phonetree/servlet/ivr/WelcomeServlet.java
Send caller input to the intended route

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

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

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.

Loading Code Samples...
Language
package com.twilio.phonetree.servlet.menu;


import com.twilio.twiml.Gather;
import com.twilio.twiml.Hangup;
import com.twilio.twiml.Say;
import com.twilio.twiml.TwiMLException;
import com.twilio.twiml.VoiceResponse;

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

public class ShowServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
            throws IOException {

        String selectedOption = servletRequest.getParameter("Digits");

        VoiceResponse response;
        switch (selectedOption) {
            case "1":
                response = getReturnInstructions();
                break;
            case "2":
                response = getPlanets();
                break;
            default:
                response = com.twilio.phonetree.servlet.common.Redirect.toMainMenu();
        }

        servletResponse.setContentType("text/xml");
        try {
            servletResponse.getWriter().write(response.toXml());
        } catch (TwiMLException e) {
            throw new RuntimeException(e);
        }
    }

    private VoiceResponse getReturnInstructions() {

        VoiceResponse response = new VoiceResponse.Builder()
                .say(new Say.Builder(
                        "To get to your extraction point, get on your bike and go down "
                        + "the street. Then Left down an alley. Avoid the police cars. Turn left "
                        + "into an unfinished housing development. Fly over the roadblock. Go "
                        + "passed the moon. Soon after you will see your mother ship.")
                        .voice(Say.Voice.ALICE)
                        .language(Say.Language.EN_GB)
                        .build())
                .say(new Say.Builder(
                        "Thank you for calling the ET Phone Home Service - the "
                        + "adventurous alien's first choice in intergalactic travel")
                        .build())
                .hangup(new Hangup())
                .build();

        return response;
    }

    private VoiceResponse getPlanets() {

        VoiceResponse response = new VoiceResponse.Builder()
                .gather(new Gather.Builder()
                        .action("/commuter/connect")
                        .numDigits(1)
                        .build())
                .say(new Say.Builder(
                        "To call the planet Broh doe As O G, press 2. To call the planet "
                        + "DuhGo bah, press 3. To call an oober asteroid to your location"
                        + ", press 4. To go back to the main menu, press the star key ")
                        .voice(Say.Voice.ALICE)
                        .language(Say.Language.EN_GB)
                        .loop(3)
                        .build()
                ).build();

        return response;
    }
}
src/main/java/com/twilio/phonetree/servlet/menu/ShowServlet.java
Main menu and return instructions

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

If the caller chooses '2', we will take them to the Planet Directory in order to collect more input.

The Planet Directory: Collect more input from the caller

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.

Loading Code Samples...
Language
package com.twilio.phonetree.servlet.menu;


import com.twilio.twiml.Gather;
import com.twilio.twiml.Hangup;
import com.twilio.twiml.Say;
import com.twilio.twiml.TwiMLException;
import com.twilio.twiml.VoiceResponse;

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

public class ShowServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
            throws IOException {

        String selectedOption = servletRequest.getParameter("Digits");

        VoiceResponse response;
        switch (selectedOption) {
            case "1":
                response = getReturnInstructions();
                break;
            case "2":
                response = getPlanets();
                break;
            default:
                response = com.twilio.phonetree.servlet.common.Redirect.toMainMenu();
        }

        servletResponse.setContentType("text/xml");
        try {
            servletResponse.getWriter().write(response.toXml());
        } catch (TwiMLException e) {
            throw new RuntimeException(e);
        }
    }

    private VoiceResponse getReturnInstructions() {

        VoiceResponse response = new VoiceResponse.Builder()
                .say(new Say.Builder(
                        "To get to your extraction point, get on your bike and go down "
                        + "the street. Then Left down an alley. Avoid the police cars. Turn left "
                        + "into an unfinished housing development. Fly over the roadblock. Go "
                        + "passed the moon. Soon after you will see your mother ship.")
                        .voice(Say.Voice.ALICE)
                        .language(Say.Language.EN_GB)
                        .build())
                .say(new Say.Builder(
                        "Thank you for calling the ET Phone Home Service - the "
                        + "adventurous alien's first choice in intergalactic travel")
                        .build())
                .hangup(new Hangup())
                .build();

        return response;
    }

    private VoiceResponse getPlanets() {

        VoiceResponse response = new VoiceResponse.Builder()
                .gather(new Gather.Builder()
                        .action("/commuter/connect")
                        .numDigits(1)
                        .build())
                .say(new Say.Builder(
                        "To call the planet Broh doe As O G, press 2. To call the planet "
                        + "DuhGo bah, press 3. To call an oober asteroid to your location"
                        + ", press 4. To go back to the main menu, press the star key ")
                        .voice(Say.Voice.ALICE)
                        .language(Say.Language.EN_GB)
                        .loop(3)
                        .build()
                ).build();

        return response;
    }
}
src/main/java/com/twilio/phonetree/servlet/menu/ShowServlet.java
Collect more input from the caller via the Planet Directory

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

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

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.

Loading Code Samples...
Language
package com.twilio.phonetree.servlet.commuter;

import com.twilio.phonetree.servlet.common.Redirect;
import com.twilio.twiml.Dial;
import com.twilio.twiml.Number;
import com.twilio.twiml.TwiMLException;
import com.twilio.twiml.VoiceResponse;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ConnectServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
            throws IOException {

        String selectedOption = servletRequest.getParameter("Digits");
        Map<String, String> optionPhones = new HashMap<>();
        optionPhones.put("2", "+12024173378");
        optionPhones.put("3", "+12027336386");
        optionPhones.put("4", "+12027336637");

        VoiceResponse twiMLResponse = optionPhones.containsKey(selectedOption)
                ? dial(optionPhones.get(selectedOption))
                : Redirect.toMainMenu();

        servletResponse.setContentType("text/xml");
        try {
            servletResponse.getWriter().write(twiMLResponse.toXml());
        } catch (TwiMLException e) {
            throw new RuntimeException(e);
        }
    }

    private VoiceResponse dial(String phoneNumber) {
        Number number = new Number.Builder(phoneNumber).build();
        return new VoiceResponse.Builder()
                .dial(new Dial.Builder().number(number).build())
                .build();
    }
}
src/main/java/com/twilio/phonetree/servlet/commuter/ConnectServlet.java
Connect to another number based on caller input

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

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

Where to Next?

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

Automated Survey (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?

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 and let us know what you build!

Agustin Camino
Kat King
Andrew Baker

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.phonetree.servlet.ivr;

import com.twilio.twiml.Gather;
import com.twilio.twiml.Play;
import com.twilio.twiml.TwiMLException;
import com.twilio.twiml.VoiceResponse;

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

public class WelcomeServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
            throws IOException {
        VoiceResponse response = new VoiceResponse.Builder()
                .gather(new Gather.Builder()
                        .action("/menu/show")
                        .numDigits(1)
                        .build())
                .play(new Play.Builder("http://howtodocs.s3.amazonaws.com/et-phone.mp3")
                        .loop(3)
                        .build())
                .build();

        servletResponse.setContentType("text/xml");
        try {
            servletResponse.getWriter().write(response.toXml());
        } catch (TwiMLException e) {
            throw new RuntimeException(e);
        }
    }
}
package com.twilio.phonetree.servlet.ivr;

import com.twilio.twiml.Gather;
import com.twilio.twiml.Play;
import com.twilio.twiml.TwiMLException;
import com.twilio.twiml.VoiceResponse;

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

public class WelcomeServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
            throws IOException {
        VoiceResponse response = new VoiceResponse.Builder()
                .gather(new Gather.Builder()
                        .action("/menu/show")
                        .numDigits(1)
                        .build())
                .play(new Play.Builder("http://howtodocs.s3.amazonaws.com/et-phone.mp3")
                        .loop(3)
                        .build())
                .build();

        servletResponse.setContentType("text/xml");
        try {
            servletResponse.getWriter().write(response.toXml());
        } catch (TwiMLException e) {
            throw new RuntimeException(e);
        }
    }
}
package com.twilio.phonetree.servlet.menu;


import com.twilio.twiml.Gather;
import com.twilio.twiml.Hangup;
import com.twilio.twiml.Say;
import com.twilio.twiml.TwiMLException;
import com.twilio.twiml.VoiceResponse;

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

public class ShowServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
            throws IOException {

        String selectedOption = servletRequest.getParameter("Digits");

        VoiceResponse response;
        switch (selectedOption) {
            case "1":
                response = getReturnInstructions();
                break;
            case "2":
                response = getPlanets();
                break;
            default:
                response = com.twilio.phonetree.servlet.common.Redirect.toMainMenu();
        }

        servletResponse.setContentType("text/xml");
        try {
            servletResponse.getWriter().write(response.toXml());
        } catch (TwiMLException e) {
            throw new RuntimeException(e);
        }
    }

    private VoiceResponse getReturnInstructions() {

        VoiceResponse response = new VoiceResponse.Builder()
                .say(new Say.Builder(
                        "To get to your extraction point, get on your bike and go down "
                        + "the street. Then Left down an alley. Avoid the police cars. Turn left "
                        + "into an unfinished housing development. Fly over the roadblock. Go "
                        + "passed the moon. Soon after you will see your mother ship.")
                        .voice(Say.Voice.ALICE)
                        .language(Say.Language.EN_GB)
                        .build())
                .say(new Say.Builder(
                        "Thank you for calling the ET Phone Home Service - the "
                        + "adventurous alien's first choice in intergalactic travel")
                        .build())
                .hangup(new Hangup())
                .build();

        return response;
    }

    private VoiceResponse getPlanets() {

        VoiceResponse response = new VoiceResponse.Builder()
                .gather(new Gather.Builder()
                        .action("/commuter/connect")
                        .numDigits(1)
                        .build())
                .say(new Say.Builder(
                        "To call the planet Broh doe As O G, press 2. To call the planet "
                        + "DuhGo bah, press 3. To call an oober asteroid to your location"
                        + ", press 4. To go back to the main menu, press the star key ")
                        .voice(Say.Voice.ALICE)
                        .language(Say.Language.EN_GB)
                        .loop(3)
                        .build()
                ).build();

        return response;
    }
}
package com.twilio.phonetree.servlet.menu;


import com.twilio.twiml.Gather;
import com.twilio.twiml.Hangup;
import com.twilio.twiml.Say;
import com.twilio.twiml.TwiMLException;
import com.twilio.twiml.VoiceResponse;

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

public class ShowServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
            throws IOException {

        String selectedOption = servletRequest.getParameter("Digits");

        VoiceResponse response;
        switch (selectedOption) {
            case "1":
                response = getReturnInstructions();
                break;
            case "2":
                response = getPlanets();
                break;
            default:
                response = com.twilio.phonetree.servlet.common.Redirect.toMainMenu();
        }

        servletResponse.setContentType("text/xml");
        try {
            servletResponse.getWriter().write(response.toXml());
        } catch (TwiMLException e) {
            throw new RuntimeException(e);
        }
    }

    private VoiceResponse getReturnInstructions() {

        VoiceResponse response = new VoiceResponse.Builder()
                .say(new Say.Builder(
                        "To get to your extraction point, get on your bike and go down "
                        + "the street. Then Left down an alley. Avoid the police cars. Turn left "
                        + "into an unfinished housing development. Fly over the roadblock. Go "
                        + "passed the moon. Soon after you will see your mother ship.")
                        .voice(Say.Voice.ALICE)
                        .language(Say.Language.EN_GB)
                        .build())
                .say(new Say.Builder(
                        "Thank you for calling the ET Phone Home Service - the "
                        + "adventurous alien's first choice in intergalactic travel")
                        .build())
                .hangup(new Hangup())
                .build();

        return response;
    }

    private VoiceResponse getPlanets() {

        VoiceResponse response = new VoiceResponse.Builder()
                .gather(new Gather.Builder()
                        .action("/commuter/connect")
                        .numDigits(1)
                        .build())
                .say(new Say.Builder(
                        "To call the planet Broh doe As O G, press 2. To call the planet "
                        + "DuhGo bah, press 3. To call an oober asteroid to your location"
                        + ", press 4. To go back to the main menu, press the star key ")
                        .voice(Say.Voice.ALICE)
                        .language(Say.Language.EN_GB)
                        .loop(3)
                        .build()
                ).build();

        return response;
    }
}
package com.twilio.phonetree.servlet.commuter;

import com.twilio.phonetree.servlet.common.Redirect;
import com.twilio.twiml.Dial;
import com.twilio.twiml.Number;
import com.twilio.twiml.TwiMLException;
import com.twilio.twiml.VoiceResponse;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ConnectServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
            throws IOException {

        String selectedOption = servletRequest.getParameter("Digits");
        Map<String, String> optionPhones = new HashMap<>();
        optionPhones.put("2", "+12024173378");
        optionPhones.put("3", "+12027336386");
        optionPhones.put("4", "+12027336637");

        VoiceResponse twiMLResponse = optionPhones.containsKey(selectedOption)
                ? dial(optionPhones.get(selectedOption))
                : Redirect.toMainMenu();

        servletResponse.setContentType("text/xml");
        try {
            servletResponse.getWriter().write(twiMLResponse.toXml());
        } catch (TwiMLException e) {
            throw new RuntimeException(e);
        }
    }

    private VoiceResponse dial(String phoneNumber) {
        Number number = new Number.Builder(phoneNumber).build();
        return new VoiceResponse.Builder()
                .dial(new Dial.Builder().number(number).build())
                .build();
    }
}