Java Servlets
Java servlets are extensions for server-side programming. The main advantages of using Java for server-side programming are that it is a powerful, general, object-oriented language and that the same language can be used on the client and server and across platforms.
Servlet Interface
The underlying servlet interface methods are invoked automatically by the server. This requires installation of the JavaServer Pages (JSP) and JavaServlets. (These have been released by Sun to Apache, referenced under the name of Tomcat.)
The servlet life-cycle begins with the execution of the servlet by the server or servlet container. The init() method of the server is executed when the servlet starts. Then, the interface provides objects with access to input and output streams that allow the program to read data from the client and send data to the client. Typically, with each request, a new thread is created with the service() method. When the container terminates the servlet, the destroy() method is called to release the servlet resources.
Two abstract classes, GenericServlet (javax.servlet) and HTTPServlet (javax.servlet.http), are the default implementations of most servlet methods. The examples in the lecture from (Internet and World Wide Web: How to Program; Deitel, Deitel, & Nieto) use the HTTPServlet class, which provides enhanced functionalities for web-based applications.
HTTPServlet
The HTTPServlet class defines methods for the HTTP request types - doGet, doPost, doDelete, doOptions, doPut, and doTrace - with doGet and doPost (called by the service() method) the most common. All of the methods receive HTTPServletRequest and HTTPServletResponse objects and return void.
Useful methods of HTTPServletRequest include:
String getParameter(String
name)
Returns the
value associated with the parameter name in the GET or POST request.
Enumeration getParameterNames()
Returns the
names of all parameters.
String[] getParameterValues(String
name)
Returns an
array of strings with the value(s) for a parameter.
Cookie[] getCookies()
Returns an
array of cookie objects.
HttpSession getSession(boolean
create)
Returns an
HttpSession object associated with the client's browser session.
Useful methods of HTTPServletResponse include:
void addCookie(Cookie cookie)
Adds a cookie
to the header of the response.
PrintWriter getWriter()
Obtains a
character based output stream.
ServletOutputStream getOutputStream()
Obtains a
byte-based output stream (e.g., for binary data).
void setContentType(String
type)
Specifies
the MIME type of the response.
Examples
Here are some simple examples on cree.unl.edu.
Here are some examples.