previous | index | next

Creating the Response Text

The Ajax servlet gets the submitted zip code from the request parameter:
public class AjaxServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException, IOException {
        response.setContentType("text/plain");
        response.setHeader("Cache-Control", "no-cache");
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(getResponseForZip(request.getParameter("zip")));
    }

    private String getResponseForZip(String zip) {
        return "97402".equals(zip) ? "Eugene,Oregon" : "NO DATA,NO DATA";
    }
}
In our example, the Ajax servlet creates a canned response for Eugene, Oregon, only.

A real application would access a database of zip codes to find the corresponding city and state.


previous | index | next