Skip to contentSkip to navigationSkip to topbar
On this page

Create an SMS Conversation in Java


How do you turn a handful of isolated messages to and from the same party into a true conversation? You need some way to remember state between each message that is exchanged. This is because SMS is a stateless protocol. Building traditional web applications has this same hurdle, as HTTP is also a stateless protocol. This problem has been solved for web applications through the use of HTTP cookies and, rather than reinvent the wheel, the Twilio Messaging API uses the same solution.

This guide will show you how to use Programmable Messaging(link takes you to an external page) to accomplish this in your Java Servlets application. The code snippets in this guide are written using Java and require the Java JDK 7 or higher. They also make use of the Twilio Java SDK(link takes you to an external page).

If you haven't written your own SMS webhooks with Java and Servlets before, you may want to first check out our guide, Receive and Reply to SMS and MMS Messages in Java. Ready to go? Let's get started!

(information)

Info

Twilio Conversations, a more recent product offering, is an omni-channel messaging platform that allows you to build engaging conversational, two-way messaging experiences. Be sure to check out our Conversations product to see if it's a better fit for your needs.


Using HTTP Cookies with Webhooks

using-http-cookies-with-webhooks page anchor

In web apps, you write a cookie to keep "statefulness" between separate requests from the same browser. Similarly, SMS messages are independent communications between two parties, so Twilio allows you to tie them together as a logical session via cookies. This means you can use server-side sessions to keep track of application state between requests. How cool is that? Twilio will expire the cookies for that conversation after four hours of inactivity, as if the user "closed the browser."

Storing Conversation Data

storing-conversation-data page anchor

The cookies let you share state across multiple messages allowing you to treat separate messages as a conversation, and store data about the conversation in the cookies for future reference.

You can store the data directly in a cookie, or you can use a session state management framework. The code sample below does the latter, using the Interface HttpSession(link takes you to an external page) available for Java Servlets.


Track SMS Conversations using a Session

track-sms-conversations-using-a-session page anchor

Let's try using session counters to see if a particular user has messaged us before. If they're a new sender, we'll thank them for the new message. If they've sent us messages before, we'll specify how many messages we've gotten from them.

Tracking SMS Conversations using CookiesLink to code sample: Tracking SMS Conversations using Cookies
1
import java.io.IOException;
2
import java.util.HashMap;
3
4
import javax.servlet.http.HttpServlet;
5
import javax.servlet.http.HttpServletRequest;
6
import javax.servlet.http.HttpServletResponse;
7
import javax.servlet.http.HttpSession;
8
9
import com.twilio.twiml.messaging.Body;
10
import com.twilio.twiml.messaging.Message;
11
import com.twilio.twiml.MessagingResponse;
12
import com.twilio.twiml.TwiMLException;
13
14
public class TwilioServlet extends HttpServlet {
15
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
16
HttpSession session = request.getSession(true);
17
Integer counter = (Integer) session.getAttribute("counter");
18
if (counter == null) {
19
counter = new Integer(0);
20
}
21
22
/* Increment the counter by one, and store the count in the session. */
23
int count = counter.intValue();
24
count++;
25
session.setAttribute("counter", new Integer(count));
26
27
// Create a dict of people we know.
28
HashMap<String, String> callers = new HashMap<String, String>();
29
callers.put("+14158675308", "Rey");
30
callers.put("+12349013030", "Finn");
31
callers.put("+12348134522", "Chewy");
32
33
String fromNumber = request.getParameter("From");
34
String toNumber = request.getParameter("To");
35
String fromName = callers.get(fromNumber);
36
if (fromName == null) {
37
// Use the caller's name
38
fromName = "Friend";
39
}
40
41
String message =
42
fromName + " has messaged " + toNumber + " " + String.valueOf(count) + " times.";
43
44
// Create a TwiML response and add our friendly message.
45
Message sms = new Message.Builder().body(new Body(message)).build();
46
MessagingResponse twimlResponse = new MessagingResponse.Builder().message(sms).build();
47
48
response.setContentType("application/xml");
49
50
try {
51
response.getWriter().print(twimlResponse.toXml());
52
} catch (TwiMLException e) {
53
e.printStackTrace();
54
}
55
}
56
}

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.