Servlets are invoked when an HTTP request references the servlet, either directly as a Java servlet, or indirectly as a JSP file. Some of the most common tasks a servlet performs are accessing the information stored within the HTTP request, processing the information, and returning results to the client as part of an HTTP response.
HTTP requests contain information sent to the servlet from the client. For example, if the servlet is invoked by a form, the servlet accesses the form data stored in the request before processing. The form data might contain login information used to verify a user, registration information written to a database, or information about a product added to a user's shopping cart.
You can access HTTP request information in a servlet and a JSP:
javax.servlet.HttpServletRequest object, which defines methods that you can use to access the information stored within the request.
javax.servlet.HttpServletRequest object.Servlets answer a request by constructing an HTTP response and sending that response back to the client. Within your servlet, you access the HTTP response to write information within the response sent back to the client.
You can access HTTP response information in a servlet and a JSP:
javax.servlet.HttpServletResponse object, which defines methods for accessing the information stored within the response.
javax.servlet.HttpServletResponse object.The HTTP response includes an output stream for sending results back to the client.
The request and response objects have many methods that you use to process requests from clients. The following example servlet reflects on these objects and shows you the methods and their return types:
...
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
Object object = null;
String targetClass = "javax.servlet.ServletConfig"; //default
String checkReq = req.getParameter("targetClass");
if (checkReq != null) {
targetClass = checkReq;
}
if (targetClass.equals("javax.servlet.ServletContext")) {
object = getServletContext();
}
if (targetClass.equals("javax.servlet.ServletConfig")) {
object = getServletConfig();
}
...
try {
Class c = Class.forName(targetClass);
Method[] meths = c.getMethods();
Object[] arguments = new Object[] {};
for (int i=0; i<meths.length; i++) {
String methodName = meths[i].getName();
String returnType = meths[i].getReturnType().getName();
String desc = meths[i].toString();
Class[] parameterTypes = meths[i].getParameterTypes();
int m = c.getModifiers();
out.println("<TR><TD><I>" + methodName + "</I></TD><TD>" + returnType + "</TD><TD>" + desc + "</TD>");
}
} catch (Exception e) {}
...
To see a sample servlet, start the samples JRun server and open a browser to http://localhost:8200/techniques.
The servlet request object provides the same information about the environment that common CGI environment variables provide.The following table lists the request object's methods and their corresponding CGI environment variables: