The following section provides some additional information from the industry perspective that you can share with the students:
Getting All Request Headers
Many reusable servlet codes especially the ones used for parsing and filtering parameters are made generic. That is, instead of handling or pre-knowing any particular request parameter they are developed to serve a general purpose to be used with all cases. Following servlet code prints all the values for all the request parameters:
Enumeration e = request.getParameterNames();
while ( e.hasMoreElements() )
{
String name = (String)e.nextElement();
String values[] = request.getParameterValues( name );
for( int count = 0; count < values.length; count++ )
{
out.println( count + ” ” + name + ” = ” + value[ count ] );
}
}
One of the possible uses of the above code is in validating a multiple choice question. If user has not selected a value then this can easily be determined by looping though all the request parameters.
Sending Error Codes
HTTP protocol has well-defined set of error codes in 4xx series, which means error generated due to client and 5xx series, which means error generated on server. Many browsers have default page implementations for error codes to provide more information regarding the error to client. Servers also allow customizations. Using these customizations user can be presented with a specific page, on generation of certain well-known error;. One of the most common examples of this is 404 error. It is generated when requested resource is not found. Many Websites takes the user to home page on 404 or presents the user search interface. Using servlet, API sending a particular error code is easy. Although you can pass any number as error code, HttpServletResponse class provides a list of common codes as
constants. For more information, see the documentation of class. Following code sends 401 or UNAUTHORIZED error code if client cannot be validated.
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType(“text/plain”);
PrintWriter out = res.getWriter();
HttpSession check = request.getSession(false);
String auth = check.getAttribute( “Authorize” );
if ( auth == null )
{
res.sendError(res.SC_UNAUTHORIZED);
}
else
{
res.sendRedirect( “some_url” );
}
}
sendError() method can only be used if no content is sent to the client. It content has been sent to the client then invoking sendError will throw and exception