|
Handling requests
You could simply call the above runScript() method to execute the script that is mapped to the URL of the HTTP request. In a real application, however, you'll probably want to do some initialization before running the script and some finalization after the script's execution.
It is possible to run multiple scripts, sequentially, in the same context. For example, a script could define a set of variables and functions. Then, another script could do some processing, using the variables and functions of the previous script that was executed in the same context.
The servlet's handleRequest() method (shown in Listing 14) sets the HTTP headers, runs the init.jss script, removes the context path from the request's URI, executes the script that has the obtained URI, and then runs another script named finalize.jss.
Listing 14. The handleRequest() method of JSServlet
public class JSServlet extends HttpServlet {
...
protected void handleRequest(
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (cacheControlHeader != null)
response.setHeader("Cache-Control", cacheControlHeader);
if (contentTypeHeader != null)
response.setContentType(contentTypeHeader);
ScriptContext scriptContext = createScriptContext(request, response);
try {
runScript("/init.jss", scriptContext);
String uri = request.getRequestURI();
uri = uri.substring(request.getContextPath().length());
try {
runScript(uri, scriptContext);
} catch (FileNotFoundException x) {
response.sendError(404, request.getRequestURI());
}
runScript("/finalize.jss", scriptContext);
} catch (ScriptException x) {
x.printStackTrace(response.getWriter());
throw new ServletException(x);
}
}
...
}
The doGet() and doPost() methods (see Listing 15) of JSServlet call handleRequest().
Listing 15. The doGet() and doPost() methods of JSServlet
public class JSServlet extends HttpServlet {
...
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
handleRequest(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
handleRequest(request, response);
}
} |
|