Java-Web:Exercises - Servlet serving XML or JSON

From Juneday education
Jump to: navigation, search

Work in progress


The purpose of this exercise is to prepare you for the assignment with the Student data servlet and the Android application.

In order to let the servlet decide what format for the data so produce and send, we will use GET parameters (parameters part of the URL for a request to a web server).

To get the parameter format, for instance, you create a String reference in the doGet() method, and ask the request object for the named parameter:

    String format = request.getParameter("format");

Note that if the parameter is missing, you'll get null back.

After getting the format parameter, you can use a switch-case, an if statement or (better) some kind of factory to get the right kind of formatter capabilities for your data.


Get the code for the presentation in the previous chapter. Add a format parameter called "html" which, if present, creates an HTML response with the data in an HTML table.

The source code is in the java-web repository of our github in this directory.

Note that when we say "add a parameter", you are actually adding the capability of acting on that parameter. It is the user/client who provides the actual parameter as part of the request, e.g. like this:

$ lwp-request http://localhost:8080/dataservlet?format=xml
<?xml version="1.0" encoding="utf-8"?>
 <street-address>Skidrow 88</street-address>
  <home>031-90 51 06</home>


In order to compile the DataServlet, you can use a command-line similar to this (you'll need to locate the servlet-api.jar, winstone.jar and javax.json.jar files accordingly) - note that it is one long line:

$ javac -cp .:../../winstone-intro/servlet-example/exercises/servlet-api.jar:webroot/WEB-INF/lib/*  webroot/WEB-INF/classes/student/servlets/ && java -jar jenkins-winstone-0.9.10-jenkins-47.jar --webroot=webroot

HTML tip

The table in HTML could look something like this:

    <title>Hanky contact info</title>
      td{ vertical-align: top; }
        <th>first name</th><th>last name</th><th>age</th><th>address></th><th>state</th><th>phone numbers</th>
        <td>Hanky</td><td>Sandycleavage</td><td>65</td><td>Skidrow 88</td><td>VGR</td>
            <li>031-90 51 06</li>

As you probably can see, we are not very good at web design, so feel free to make a fancier table or presentation.

Challenge - write and use a factory instead

Review the chapter about using a factory for Json or XML, and write a similar factory for your servlet. You may use a simpler version of a factory, like a factory method which takes the format as a String parameter.



Currently no more chapters. But check out the assignments:

« PreviousBook TOCNext »