Rate this page:

Call Tracking with Java and Servlets

Twilio is launching a new Console. Some screenshots on this page may show the Legacy Console and therefore may no longer be accurate. We are working to update all screenshots to reflect the new Console experience. Learn more about the new Console.

This Java Servlets web application shows how you can use Twilio to track the effectiveness of different marketing channels.

This application has three main features:

  • It purchases phone numbers from Twilio to use in different marketing campaigns (like a billboard or a bus advertisement)
  • It forwards incoming calls for those phone numbers to a salesperson
  • It displays charts showing data about the phone numbers and the calls they receive

Check out how used Twilio to build a call tracking platform for healthcare providers.

In this tutorial, we'll point out the key bits of code that make this application work. Check out the project README on GitHub to see how to run the code yourself.

Let's get started!

Search for Available Phone Numbers

Call tracking requires us to search for and buy phone numbers on demand, associating a specific phone number with a lead source. This class uses the Twilio Java Helper Library to search for phone numbers by area code and return a list of numbers that are available for purchase.


        Search Phone Numbers


        Now let's see how we will display these numbers for the user to purchase them and enable their campaigns.

        Display available phone numbers

        Display Available Phone Numbers

        We display a form to the user on the app's home page which allows them to search for a new phone number by area code. At the controller level we use the TwilioServices instances we created earlier to actually search for numbers. This will render the view that contains a list of numbers they can choose to buy.


              Available Phone Numbers


              We've seen how we can display available phone numbers for purchase with the help of the Twilio C# helper library. Now let's look at how we can buy an available phone number.

              How we buy a phone number

              Buy a Phone Number

              Our PurchasePhoneNumber method takes two parameters, the first one is a phone number and the second one is the application SID. Now our Twilio API client can purchase the available phone number our user chooses.


                    Purchase Phone Number


                    If you don't know where you can get this application SID, don't panic, the next step will show you how.

                    See where we get that application SID

                    Set webhook URLs in a TwiML Application

                    When we purchase a phone number, we specify a voice application SID. This is an identifier for a TwiML application, which you can create through the REST API or your Twilio Console.

                    Create TwiML App

                    Learn how to associate a phone number

                    Associate a Phone Number with a Lead Source

                    Once we search for and buy a Twilio number, we need to associate it with a lead source in our database. This is the core of a call tracking application. Any phone calls to our new Twilio number will be attributed to this source.


                          Associate a Phone Number with a Lead Source


                          So far our method for creating a Lead Source and associating a Twilio phone number with it is pretty straightforward. Now let's have a closer look at our Lead Source model which will store this information.

                          How we define the lead source model

                          The LeadSource Model

                          The LeadSource model associates a Twilio number to a named lead source (like "Wall Street Journal Ad" or "Dancing guy with sign"). It also tracks a phone number to which we'd like all the calls redirected, like your sales or support help line.


                                Lead Source Model


                                As the application will be collecting leads and associating them to each LeadSource or campaign, it is necessary to have a Lead model as well to keep track of each Lead as it comes in and associate it to the LeadSource.

                                Let's see what the Lead model looks like

                                The Lead Model

                                A Lead represents a phone call generated by a LeadSource. Each time somebody calls a phone number associated with a LeadSource, we'll use the Lead model to record some of the data Twilio gives us about their call.


                                      Lead Model


                                      The backend part of the code which creates a LeadSource as well as a Twilio Number is complete. The next part of the application will be the webhooks that will handle incoming calls and forward them to the appropriate sales team member. Let's us see the way these webhooks are built.

                                      Learn how to forward calls

                                      Forward Calls and Create Leads

                                      Whenever a customer calls one of our Twilio numbers, Twilio will send a POST request to the URL associated with this action (should be /lead).

                                      We use the incoming call data to create a new Lead for a LeadSource, then return TwiML that connects our caller with the forwardingNumber of our LeadSource.


                                            Call Forwarding


                                            Once we have forwarded calls and created leads, we will have a lot of incoming calls that will create leads, and that will be data for us but we need to transform that data into information in order to get benefits from it. So, let's see how we get statistics from these sources on the next step.

                                            See how to get statistics from lead sources

                                            Get Statistics about Our Lead Sources

                                            One useful statistic we can get from our data is how many calls each LeadSource has received. We query over LeadSource and count its Lead models.


                                                  Leads By Source Stats


                                                  Up until this point, we have been focusing on the backend code to our application. Which is ready to start handling incoming calls or leads. Next, let's turn our attention to the client side. Which, in this case, is a simple Javascript application, along with Chart.js which will render these stats in an appropriate way.

                                                  How we draw the statistics with chart.js

                                                  Visualize our statistics with Chart.js

                                                  Back on the home page, we fetch call tracking statistics in JSON from the server using Jackson/ObjectMapper and jQuery. We display the stats in colorful pie charts we create with Chart.js.


                                                        Visualize our statistics with Chart.js


                                                        That's it! Our Java Servlet application is now ready to purchase new phone numbers, forward incoming calls, and record some statistics for our business.

                                                        Where to Next?

                                                        Where to Next?

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

                                                        SMS and MMS notifications

                                                        Build a server notification system that will alert all administrators via SMS when a server outage occurs.

                                                        Click To Call

                                                        Convert web traffic into phone calls with the click of a button.

                                                        Did this help?

                                                        Thanks for checking this tutorial out! If you have any feedback to share with us please contact us on Twitter, we'd love to hear it.

                                                        David Prothero Kat King Andrew Baker Jose Oliveros
                                                        Rate this page:

                                                        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 by visiting Twilio's Community Forums or browsing the Twilio tag on Stack Overflow.


                                                              Thank you for your feedback!

                                                              We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

                                                              Sending your feedback...
                                                              🎉 Thank you for your feedback!
                                                              Something went wrong. Please try again.

                                                              Thanks for your feedback!

                                                              Refer us and get $10 in 3 simple steps!

                                                              Step 1

                                                              Get link

                                                              Get a free personal referral link here

                                                              Step 2

                                                              Give $10

                                                              Your user signs up and upgrade using link

                                                              Step 3

                                                              Get $10

                                                              1,250 free SMSes
                                                              OR 1,000 free voice mins
                                                              OR 12,000 chats
                                                              OR more