Getting Started With Project jMaki for the GlassFish v3 Application Server

ProcedureWriting a Servlet to Obtain the Server-Side Data for the Handler

While performing the previous task, you added an Ajax call to the Service servlet to obtain the values from StateBean. You'll create the servlet with this task.

  1. Expand the plotCity > Source Packages > plotCity node.

  2. Right-click on the plotCity package icon and select New > Servlet.

  3. Enter Service for the class name.

  4. Click Finish.

  5. Delete everything inside the servlet class so that all that the file contains are the package statement, the import statements automatically generated, and the following empty servlet class:

    public class Service extends HTTPServlet{}
  6. Add the following private variable declaration:

    private ServletContext context;
  7. Add the following init method to the class:

    @Override
    public void init(ServletConfig config) 
    	throws ServletException {
    	this.context = config.getServletContext();
    }
  8. Add the following doPost method to the class:

    public void doPost(
    	HttpServletRequest request, HttpServletResponse response) 
    	throws IOException, ServletException {
    	HttpSession session = request.getSession();
    	StateBean stateBean = 
    		(StateBean)session.getAttribute("StateBean");
    	String cityData = new String();
    	String message = request.getParameter("message");
    	try{
    		cityData = stateBean.getNewCities(message);
    	} catch (Exception e){
    		System.out.println("could not get city data");
    	}
    	PrintWriter writer = response.getWriter();
    	writer.write(cityData);
    	session.setAttribute("stateBean", stateBean);
    }

    This method gets the message parameter from the request, passes it to getNewCities, and passes the resulting list of cities to the response.

  9. Save the file.