Skip to contentSkip to navigationSkip to topbar
Rate this page:
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 Programmable Messaging(link takes you to an external page) makes this easy for you and 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 Cookies

tracking-sms-conversations-using-cookies page anchor
Java

_56
import java.io.IOException;
_56
import java.util.HashMap;
_56
_56
import javax.servlet.http.HttpServlet;
_56
import javax.servlet.http.HttpServletRequest;
_56
import javax.servlet.http.HttpServletResponse;
_56
import javax.servlet.http.HttpSession;
_56
_56
import com.twilio.twiml.messaging.Body;
_56
import com.twilio.twiml.messaging.Message;
_56
import com.twilio.twiml.MessagingResponse;
_56
import com.twilio.twiml.TwiMLException;
_56
_56
public class TwilioServlet extends HttpServlet {
_56
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
_56
HttpSession session = request.getSession(true);
_56
Integer counter = (Integer) session.getAttribute("counter");
_56
if (counter == null) {
_56
counter = new Integer(0);
_56
}
_56
_56
/* Increment the counter by one, and store the count in the session. */
_56
int count = counter.intValue();
_56
count++;
_56
session.setAttribute("counter", new Integer(count));
_56
_56
// Create a dict of people we know.
_56
HashMap<String, String> callers = new HashMap<String, String>();
_56
callers.put("+14158675308", "Rey");
_56
callers.put("+12349013030", "Finn");
_56
callers.put("+12348134522", "Chewy");
_56
_56
String fromNumber = request.getParameter("From");
_56
String toNumber = request.getParameter("To");
_56
String fromName = callers.get(fromNumber);
_56
if (fromName == null) {
_56
// Use the caller's name
_56
fromName = "Friend";
_56
}
_56
_56
String message =
_56
fromName + " has messaged " + toNumber + " " + String.valueOf(count) + " times.";
_56
_56
// Create a TwiML response and add our friendly message.
_56
Message sms = new Message.Builder().body(new Body(message)).build();
_56
MessagingResponse twimlResponse = new MessagingResponse.Builder().message(sms).build();
_56
_56
response.setContentType("application/xml");
_56
_56
try {
_56
response.getWriter().print(twimlResponse.toXml());
_56
} catch (TwiMLException e) {
_56
e.printStackTrace();
_56
}
_56
}
_56
}


Rate this page: