Java-Web:Exercises - RequestDispatch

From Juneday education
Jump to: navigation, search

Exercises

Get the source code

Download the source code from our github repo.

There are scripts to build and run the exercise servlets.

Remember that on Windows, you must fix the class path to use semicolon rather than colon.

Make the servlet dispatch

There are three servlets installed in the exercise directory:

$ lwp-request -m GET 'http://localhost:8080/xmlorjson?format=json'
$ lwp-request -m GET 'http://localhost:8080/xmldummy'
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<MESSAGE>student.servlets.XMLDummy</MESSAGE>
$ lwp-request -m GET 'http://localhost:8080/jsondummy'
{"json-reply-from":"student.servlets.JsonDummy"}

As you see, the first one, xmlorjson, doesn't do its job properly. It should look at the format parameter, and dispatch (send the request on) to one of the other servlets. A dispatch is not visible to the client - it looks as if the servlet it repsonding on its own, while it is really dispatching the work to another servlet.

Open the servlet for xmlorjson and add the dispatches to the other two servlets in the correct place. Remember that the dispatch should use the servlet name as the argument (as a String).

Expand using link to the right to see a hint.

For instance:

request.getRequestDispatcher("xmldummy")
       .forward(request, response);

Links

Source code

Navigation

Up next: XML!

« PreviousBook TOCNext »